-2

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?

Mike
  • 1,017
  • 4
  • 19
  • 34
  • 3
    So you want to take `768` from `768 - Hello World`, well. this is a simple question have you tried anything, even a quick search? – sujith karivelil Sep 28 '16 at 06:11
  • 1
    Will the integer always be at the start? What if there are two integers? What about `5.5 - Hello World`? Will the number always be followed by ` - `? How you choose to extract the numeric part of the string will very much depend on what inputs you need to handle. You *might* want to use a regular expression, or it *might* be as simple as finding the substring before the first space. – Jon Skeet Sep 28 '16 at 06:11
  • 1
    This is the format i get always and there will be no decimals. There are spaces between the integer and dash as well as btween dash and the string – Mike Sep 28 '16 at 06:13
  • @F.Klein, It worked thank you. – Mike Sep 28 '16 at 06:21

3 Answers3

4
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();
}
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
1

Split by Space and take the first element. Parse it as integer.

string str = "768 - Hello World";
int i = Int32.Parse(str.Split(' ').First());
Sarvesh Mishra
  • 2,014
  • 15
  • 30
1
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;
}