-
September 7th, 2012, 09:02 AM
#1
How to extract the numbers out a string.
Hi, I am using a format like this: "xxx/xxx p:xxx" (xxx represents an integer number).
How can I get the numbers seperatly?f.e: 450/45 p:33 How to extract the numbers 450,
45 and 33 from the string. Who can help me? Greetings, Peter Kiers
-
September 7th, 2012, 01:14 PM
#2
Re: How to extract the numbers out a string.
You can use the Split( ) method: Overloaded. Identifies the substrings in the string that are delimited by one or more characters specified in an array, then places the substrings into a string array. string [ ] sn = sValue.Split(' '); foreach (string i in sn) Console.WriteLine(i);
Or ToCharArray( ) method: char [ ] cArray = sValue.ToCharArray(0, 2); Console.WriteLine(cArray);
Hope that helps.
-
September 8th, 2012, 02:10 AM
#3
Re: How to extract the numbers out a string.
Code:
class Program
{
static void Main(string[] args)
{
var sb = new StringBuilder("450/45 p:33");
sb.Replace('/', ' ');
sb.Replace("p:", "");
var index = 1;
foreach (var s in sb.ToString().Split(new char[] { ' ' }))
{
var value = Int32.Parse(s); // Not strickly necessary, but gives you value as Int type
Console.WriteLine(String.Format( "Number {0}: {1}", index++, value));
}
}
}
Outputs:
Number 1: 450
Number 2: 45
Number 3: 33
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|