简体   繁体   中英

How to convert a string with comma to integer in C#

For example I have a string " 99,999 ABC XYZ " Now I want to convert to integer " 99999 "

I have made a code that worked:

 var regex = new Regex("[A-z]");
 linksOnPage = regex.Replace(linksOnPage, "");

 regex = new Regex(" ");
 linksOnPage = regex.Replace(linksOnPage, "");

 int noPage = int.Parse(regex.Replace(linksOnPage, ""), 
                        NumberStyles.AllowThousands);

But I feel it's not good enough, can anyone help me to make it shorter?

This Regex will remove all the letters and spaces:

var regex = new Regex(" |[A-z]");
linksOnPage = regex.Replace(linksOnPage, "");

You could use int.Parse and add the NumberStyles.AllowThousands flag:

int num = int.Parse(linksOnPage , NumberStyles.AllowThousands);

Or int.TryParse letting you know if the operation succeeded:

int num;
if (int.TryParse(linksOnPage , NumberStyles.AllowThousands,
                 CultureInfo.InvariantCulture, out num))
{
    // parse successful, use 'num'
}

Or you can also try this:

int num = int.Parse(linksOnPage.Replace(",", ""));

This would be my approach, it's not really shorter though:

    public static void Main(string[] args)
    {
       string input = "99,999 ABC XYZ";
       var chars = input.ToCharArray().ToList();
       var builder = new StringBuilder();
       foreach (var character in chars)
       {
           if (char.IsNumber(character))
               builder.Append(character); 
       }

       int result = 0;
       int.TryParse(builder.ToString(), out result);

       Console.WriteLine(result);
       Console.ReadKey();
    }

you could do something like this:

    int? ParseIntFromString( string s )
    {
        Match m = rxInt.Match(s) ;
        int? value = m.Success ? int.Parse( m.Value , NumberStyles.AllowLeadingSign|NumberStyles.AllowThousands ) : (int?)null ;
        return value ;
    }
    static Regex rxInt = new Regex( @"^-?\d{1,3}(,\d\d\d)*");

the return value is null if no integer value was found and the parsed value if it was.

Note that the match is anchored at start-of-string via ^ ; if you want to match an number anywhere in the string, simply remove it.

You could also kick it old-school and do something like this:

public int? ParseIntFromString( string s )
{
  bool found = false ;
  int  acc   = 0 ;
  foreach( char c in s.Where( x => char.IsDigit )
  {
    found = true ;
    acc += c - '0' ;
  }
  return found ? (int?)acc : (int?) null ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM