Using LINQ to parse the numbers from a string

前端 未结 7 1478
忘掉有多难
忘掉有多难 2021-02-19 22:00

Is it possible to write a query where we get all those characters that could be parsed into int from any given string?

For example we have a string like: \"$%^DDFG

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 22:33

    string testString = "$%^DDFG 6 7 23 1";
    string cleaned = new string(testString.ToCharArray()
        .Where(c => char.IsNumber(c)).Take(3).ToArray());
    

    If you want to use a white list (not always numbers):

    char[] acceptedChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    string cleaned = new string(testString.ToCharArray()
        .Where(c => acceptedChars.Contains(c)).Take(3).ToArray());
    

提交回复
热议问题