开发者

the easiest way to get number from string

开发者 https://www.devze.com 2023-02-24 21:05 出处:网络
i want to retrive some number from string, for example \"valueID = 234232\" or \"valueID = 2\" or \"value开发者_运维知识库ID=23\" or \"valueID= 2\" or \"valueID =234\", so what is the easiest way to g

i want to retrive some number from string, for example "valueID = 234232" or "valueID = 2" or "value开发者_运维知识库ID=23" or "valueID= 2" or "valueID =234", so what is the easiest way to get this number assuming that after this number is space " " or end of line?


string input = "valueID = 234232";
var split = input.Split(new char[] {'='});
int value = int.Parse(split[1].Trim());


As long as your sure there will be a number in there

int.parse( Regex.match(String, @"\d+").value)


How about using a regex:

  Match match = Regex.Match(input, @"\d+");
  if (match.Success) 
  {
     number = int.Parse(match.Value);
  }


Here's some flexible code I use all the time for this sort of thing:

public const string FilterDigits = "0123456789";
public const string FilterLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

/// <summary>
/// Strips away any characters not defined in validChars and returns the result.
/// </summary>
public static string FilterTo(string text, string validChars)
{
StringBuilder Result = new StringBuilder();

for (int i = 1; i <= text.Length; i++) {
    char CurrentChar = Convert.ToChar(Strings.Mid(text, i, 1));

    if (validChars.Contains(CurrentChar)) {
        Result.Append(CurrentChar);
    }
}

return Result.ToString;
}

Then you can just call:

 int.parse(FilterTo("valueID=23", FilterDigits));

It could also be turned into a handy extension method, then you could do:

 int.parse("valueID=23".FilterTo(FilterDigits));


Once you've parsed out your potential number (through regex, split, substr, etc), TryParse is a great improvement (since .NET 3.5 at least):

string myPotentialNumber = "1";
int myNumber;
bool isNumber = int.TryParse(myPotentialNumber, out myNumber);

if( isNumber )
{
   //do something
}
else
{
   //throw error
}

TryParse() is exception safe, which makes it a bit faster and cleaner for many types of conversions.

0

精彩评论

暂无评论...
验证码 换一张
取 消