I want to get a integer value in a string. Any suggessions?
Take this as an example.
768 - Hello World
According to the preceding string i want to get the 768 to a variable. How to do so?
I want to get a integer value in a string. Any suggessions?
Take this as an example.
768 - Hello World
According to the preceding string i want to get the 768 to a variable. How to do so?
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.
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();
}
Split by Space and take the first element. Parse it as integer.
string str = "768 - Hello World";
int i = Int32.Parse(str.Split(' ').First());
public int GetLeadingIntegerFromString(string myString)
{
if (string.IsNullOrWhiteSpace(myString))
return;
var parts = myString.Split('-');
if (parts.Length < 1)
return;
var number = int.Parse(parts[0].Trim());
return number;
}