I want to get a integer value in a string. Any suggessions?
Take this as an example.
768 - Hello World
Int32.Parse(Regex.Match(some_string, @"\d+").Value);
some_string represents a variable that is of a string data type. The regex will return the very first number encountered starting from left. In your example it's 768. If the some_string contains 'hello 768", it will still return 768.
EDIT:
If you want to do without using regex, you can do so using a simple loop-
public string GetFirstNumber(string some_string) {
if (string.IsNullOrEmpty(some_string)) {
return string.Empty; // You could return null to indicate no data
}
StringBuilder sb = new StringBuilder();
bool found = false;
foreach(char c in some_string){
if(Char.IsDigit(c)){
sb.Append(c);
found = true;
} else if(found){
// If we have already found a digit,
// and current character is not a digit, stop looping
break;
}
}
return sb.ToString();
}