Check if a string contains one of 10 characters

前端 未结 6 930
情话喂你
情话喂你 2020-12-04 12:01

I\'m using C# and I want to check if a string contains one of ten characters, *, &, # etc etc.

What is the best way?

6条回答
  •  被撕碎了的回忆
    2020-12-04 12:22

    If you just want to see if it contains any character, I'd recommend using string.IndexOfAny, as suggested elsewhere.

    If you want to verify that a string contains exactly one of the ten characters, and only one, then it gets a bit more complicated. I believe the fastest way would be to check against an Intersection, then check for duplicates.

    private static char[] characters = new char [] { '*','&',... };
    
    public static bool ContainsOneCharacter(string text)
    {
        var intersection = text.Intersect(characters).ToList();
        if( intersection.Count != 1)
            return false; // Make sure there is only one character in the text
    
        // Get a count of all of the one found character
        if (1 == text.Count(t => t == intersection[0]) )
            return true;
    
        return false;
    }
    

提交回复
热议问题