且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串是否包含给定字符列表之外的字符

更新时间:2023-02-26 11:25:36

这很容易实现. string 类型实现了 IEnumerable< char> ,因此您可以使用LINQ All 方法来检查其所有字符是否都满足谓词.在您的情况下,谓词是每个字符都包含在 allowedChars 集中,因此您可以使用 Contains 方法:

This is straightforward to achieve. The string type implements IEnumerable<char>, so you can use the LINQ All method to check that all its characters satisfy a predicate. In your case, the predicate is that each character is contained in the allowedChars set, so you can use the Contains method:

private static bool CheckInvalidInput(string stringToCheck, IEnumerable<char> allowedChars)
{
    return stringToCheck.All(allowedChars.Contains);
}

如果您的 allowedChars 设置变大,则需要将其转换为 HashSet< char> 以获得更好的性能.

If your allowedChars set gets large, you would want to convert it to a HashSet<char> for better performance.

完整示例:

using System;
using System.Linq;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        // var allowedChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' };
        var allowedChars = "0123456789.";

        Console.WriteLine(CheckInvalidInput("54323.5", allowedChars));   // True
        Console.WriteLine(CheckInvalidInput("543g23.5", allowedChars));  // False
    }

    private static bool CheckInvalidInput(string stringToCheck, IEnumerable<char> allowedChars)
    {
        return stringToCheck.All(allowedChars.Contains);
    }
}