简体   繁体   中英

Get non numeric values from string value c#

I have value like below

string value = "11,.Ad23";
int n;
bool isNumeric = int.TryParse(value, out n);

I control if string is numeric or not.If string is not numeric and has non numeric i need to get non numeric values as below

Result must be as below

,.Ad

How can i do this in c# ?

If it doesn't matter if the non-digits are consecutive, it's simple:

string nonNumericValue = string.Concat(value.Where(c => !Char.IsDigit(c)));

Online Demo: http://ideone.com/croMht

If you use .NET 3.5. as mentioned in the comment there was no overload of String.Concat (or String.Join as in Dmytris answer ) that takes an IEnumerable<string> , so you need to create an array:

string nonNumericValue = string.Concat(value.Where(c => !Char.IsDigit(c)).ToArray());

That takes all non-digits. If you instead want to take the middle part, so skip the digits, then take all until the the next digits:

string nonNumericValue = string.Concat(value.SkipWhile(Char.IsDigit)
                                            .TakeWhile(c => !Char.IsDigit(c)));

Regular expression solution (glue together all non-numeric values):

  String source = "11,.Ad23";
  String result = String.Join("", Regex
    .Matches(source, @"\D{1}")
    .OfType<Match>()
    .Select(item => item.Value));

Edit: it seems that you use and old version of .Net, in that case you can use straightforward code without RegEx , Linq etc:

  String source = "11,.Ad23";

  StringBuilder sb = new StringBuilder(source.Length);

  foreach (Char ch in source)
    if (!Char.IsDigit(ch))
      sb.Append(ch);

  String result = sb.ToString();

Although I like the solution proposed I think a more efficent way would be using regular expressions such as

[^\\D]

Which called as

var regex = new Regex(@"[^\D]");
var nonNumeric = regex.Replace("11,.Ad23", "")); 

Which returns:

,.Ad

Would a LINQ solution work for you?

string value = "11,.Ad23";
var result = new string(value.Where(x => !char.IsDigit(x)).ToArray());

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