Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a number from a string with non-digits in between

Tags:

c#

I am working on .NET project and I am trying to parse only the numeric value from string. For example,

string s = "12ACD";
int t = someparefun(s); 
print(t) //t should be 12

A couple assumptions are

  1. The string pattern always will be number follow by characters.
  2. The number portion always will be either one or two digits value.

Is there any C# predefined function to parse the numeric value from string?

like image 707
tony Avatar asked Jul 08 '10 14:07

tony


People also ask

How to check if string contains non numeric characters in C#?

All(char. IsDigit); If you want to know whether or not a value entered into your program represents a valid integer value (in the range of int ), you can use TryParse() . Note that this approach is not the same as checking if the string contains only numbers.

How to check for digits in a string in C#?

In C#, we can use the IsDigit() method to check if a character is numeric or a digit. The IsDigit() method can be used on a single character or on a string.


1 Answers

There's no such function, at least none I know of. But one method would be to use a regular expression to remove everything that is not a number:

using System;
using System.Text.RegularExpressions;

int result =
    // The Convert (System) class comes in pretty handy every time
    // you want to convert something.
    Convert.ToInt32(
        Regex.Replace(
            "12ACD",  // Our input
            "[^0-9]", // Select everything that is not in the range of 0-9
            ""        // Replace that with an empty string.
    ));

This function will yield 12 for 12ABC, so if you need to be able to process negative numbers, you'll need a different solution. It is also not safe, if you pass it only non-digits it will yield a FormatException. Here is some example data:

"12ACD"  =>  12
"12A5"   =>  125
"CA12A"  =>  12
"-12AD"  =>  12
""       =>  FormatException
"AAAA"   =>  FormatException

A little bit more verbose but safer approach would be to use int.TryParse():

using System;
using System.Text.RegularExpression;

public static int ConvertToInt(String input)
{
    // Replace everything that is no a digit.
    String inputCleaned = Regex.Replace(input, "[^0-9]", "");

    int value = 0;

    // Tries to parse the int, returns false on failure.
    if (int.TryParse(inputCleaned, out value))
    {
        // The result from parsing can be safely returned.
        return value;
    }

    return 0; // Or any other default value.
}

Some example data again:

"12ACD"  =>  12
"12A5"   =>  125
"CA12A"  =>  12
"-12AD"  =>  12
""       =>  0
"AAAA"   =>  0

Or if you only want the first number in the string, basically stopping at meeting something that is not a digit, we suddenly also can treat negative numbers with ease:

using System;
using System.Text.RegularExpression;

public static int ConvertToInt(String input)
{
    // Matches the first numebr with or without leading minus.
    Match match = Regex.Match(input, "-?[0-9]+");

    if (match.Success)
    {
        // No need to TryParse here, the match has to be at least
        // a 1-digit number.
        return int.Parse(match.Value);
    }

    return 0; // Or any other default value.
}

And again we test it:

"12ACD"  =>  12
"12A5"   =>  12
"CA12A"  =>  12
"-12AD"  =>  -12
""       =>  0
"AAAA"   =>  0

Overall, if we're talking about user input I would consider not accepting invalid input at all, only using int.TryParse() without some additional magic and on failure informing the user that the input was suboptimal (and maybe prompting again for a valid number).

like image 51
Bobby Avatar answered Sep 24 '22 03:09

Bobby