How can I remove numbers/digits from strings in a List<string>?

北慕城南 提交于 2021-01-27 05:32:11

问题


I have a List of strings:

List<string> _words = ExtractWords(strippedHtml);

_words contains 1799 indexes; in each index there is a string.

Some of the strings contain only numbers, for example:

" 2" or "2013"

I want to remove these strings and so in the end the List will contain only strings with letters and not digits.

A string like "001hello" is OK but "001" is not OK and should be removed.


回答1:


You can use LINQ for that:

_words = _words.Where(w => w.Any(c => !Char.IsDigit(c))).ToList();

This would filter out strings that consist entirely of digits, along with empty strings.




回答2:


_words = _words.Where(w => !w.All(char.IsDigit))
               .ToList();



回答3:


For removing words that are only made of digits and whitespace:

var good = new List<string>();
var _regex = new Regex(@"^[\d\s]*$");
foreach (var s in _words) {
    if (!_regex.Match(s).Success)
        good.Add(s);
}

If you want to use LINQ something like this should do:

_words = _words.Where(w => w.Any(c => !char.IsDigit(c) && !char.IsWhiteSpace(c)))
               .ToList();



回答4:


You can use a traditional foreach and Integer.TryParse to detect numbers. This will be faster than Regex or LINQ.

var stringsWithoutNumbers = new List<string>();
foreach (var str in _words)
{
    int n;
    bool isNumeric = int.TryParse(str, out n);
    if (!isNumeric)
    {
        stringsWithoutNumbers.Add(str);
    }
}


来源:https://stackoverflow.com/questions/17349179/how-can-i-remove-numbers-digits-from-strings-in-a-liststring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!