getting number from string
How I can ge开发者_如何学Pythont number from following string:
###E[shouldbesomenumber][space or endofline]
[] here only for Illustration not present in the real string.
I am in .net 2.0.
Thanks.
I would suggest that you use regular expressions or string operations to isolate just the numeric part, and then call int.Parse
, int.TryParse
, decimal.Parse
, decimal.TryParse
etc depending on the type of number you need to parse.
The regular expression might look something like:
@"###E(-?\d+) ?$";
You'll need to change it for non-integers, of course. Sample code:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] arg)
{
Regex regex = new Regex(@"###E(-?\d+) ?$");
string text = "###E123 ";
Match match = regex.Match(text);
if (match.Success)
{
string group = match.Groups[1].Value;
int parsed = int.Parse(group);
Console.WriteLine(parsed);
}
}
}
Note that this could still fail with a number which exceeds the range of int
. (Another reason to use int.TryParse
...)
static string ExtractNumber(string text)
{
const string prefix = "###E";
int index = text.IndexOfAny(new []{' ', '\r', '\n'});
string number = text.Substring(prefix.Length, index - prefix.Length);
return number;
}
Now that your number is extracted you can parse it or use it as it is.
精彩评论