简体   繁体   中英

Trim string from behind and convert to integer

I have string for example

var str = "1,203cars";

I want to convert this number to Integer ( to remove this strange comma separator ) and to remove cars. I know I should be using String.Trim() method but I don't know how to trim from behind and remove cars and convert 1,203 to 1203 without losing data.

You can use a regular expression to get the number from the beginning of the string (which will leave out any number later in the string), then remove the separator.

Example:

string str = "1,203cars then 703bikes";

string num = Regex.Match(str, @"^[\d,]+").Value.Replace(",", String.Empty);

Then you can parse the string:

int n = Int32.Parse(num);

Explanation of the regular expression

^      =   Matches the beginning of the string
[]     =   Matches a set of characters
\d     =   Matches a digit
[\d,]  =   Matches a digit or a comma
+      =   Repeats the previos match one or more times

Using a little Linq trick:

var result = int.Parse(new string(str.Where(char.IsDigit).ToArray()));

Or, since char.IsDigit returns true for all unicode digits, here is more proper solution:

var numbers = new [] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

var result = int.Parse(new string(str.Where(numbers.Contains).ToArray()));
 var str = "1,203cars";   
 var newStr = Int32.Parse(Regex.Match(str.replace(",",""), @"\d+").Value);

由于它始终完全是“汽车”,因此您只需删除最后4个字符,然后用空字符串替换逗号即可:

int.Parse(str.Remove(str.Length-4).Replace(",",""))
    var str = "1,20.3cars";
    str = str.Replace(",", "");
    var num = int.Parse(new string(str.TakeWhile(char.IsDigit).ToArray()));

    Console.WriteLine(num);

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