从字符串值c#中获取非数字值

时间:2015-04-29 12:47:57

标签: c# string

我的价值如下

,.Ad

我控制字符串是否为数字。如果字符串不是数字且非数字,我需要获取非数字值,如下所示

结果必须如下

public void removeChildren(int index) {
    MutableTreeTableNode node = root.getChildAt(index);
    this.removeNodeFromParent(node);
}

我怎样才能在c#中做到这一点?

4 个答案:

答案 0 :(得分:8)

如果非数字是连续的并不重要,那很简单:

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

在线演示:http://ideone.com/croMht

如果使用.NET 3.5。正如评论中所提到的那样String.Concat(或Dmytris answer中的String.Join)不会超过IEnumerable<string>,因此您需要创建一个数组:

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

取所有非数字。如果你想取中间部分,那么跳过数字,然后取全部直到下一个数字:

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

答案 1 :(得分:2)

正则表达式解决方案(将所有非数字值粘合在一起):

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

编辑:您似乎使用旧版本的.Net,在这种情况下,您可以使用简单的代码而无需 RegEx Linq 等:

  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();

答案 2 :(得分:1)

虽然我喜欢提出的解决方案,但我认为更有效的方法是使用正则表达式,例如

[^\D]

其中称为

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

返回:

,.Ad

答案 3 :(得分:1)

LINQ解决方案是否适合您?

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