简体   繁体   English

如何识别字符串是否包含特定字符的多个实例?

[英]How to identify if a string contains more than one instance of a specific character?

I want to check if a string contains more than one character in the string? 我想检查字符串中是否包含多个字符? If i have a string 12121.23.2 so i want to check if it contains more than one . 如果我有一个字符串12121.23.2所以我想检查它是否包含多个。 in the string. 在字符串中。

You can compare IndexOf to LastIndexOf to check if there is more than one specific character in a string without explicit counting: 您可以将IndexOfLastIndexOf进行比较,以检查string是否存在多个特定字符而无需显式计数:

var s = "12121.23.2";
var ch = '.';
if (s.IndexOf(ch) != s.LastIndexOf(ch)) {
    ...
}

You can easily count the number of occurences of a character with LINQ: 您可以使用LINQ轻松计算角色的出现次数:

string foo = "12121.23.2";
foo.Count(c => c == '.');

If performance matters, write it yourself: 如果性能很重要,请自行编写:

public static bool ContainsDuplicateCharacter(this string s, char c)
{
    bool seenFirst = false;
    for (int i = 0; i < s.Length; i++)
    {
        if (s[i] != c)
            continue;
        if (seenFirst)
            return true;
        seenFirst = true;
    }
    return false;
}

In this way, you only make one pass through the string's contents, and you bail out as early as possible. 通过这种方式,你只需要通过字符串的内容,然后尽早拯救。 In the worst case you visit all characters only once. 在最坏的情况下,您只访问所有字符一次。 In @dasblinkenlight's answer, you would visit all characters twice, and in @mensi's answer, you have to count all instances, even though once you have two you can stop the calculation. 在@dasblinkenlight的答案中,您将访问所有字符两次,并且在@ mensi的答案中,您必须计算所有实例,即使您有两个也可以停止计算。 Further, using the Count extension method involves using an Enumerable<char> which will run more slowly than directly accessing the characters at specific indices. 此外,使用Count扩展方法涉及使用Enumerable<char> ,其运行速度比直接访问特定索引处的字符要慢。

Then you may write: 然后你可以写:

string s = "12121.23.2";

Debug.Assert(s.ContainsDuplicateCharacter('.'));
Debug.Assert(s.ContainsDuplicateCharacter('1'));
Debug.Assert(s.ContainsDuplicateCharacter('2'));
Debug.Assert(!s.ContainsDuplicateCharacter('3'));
Debug.Assert(!s.ContainsDuplicateCharacter('Z'));

I also think it's nicer to have a function that explains exactly what you're trying to achieve. 我还认为拥有一个能够准确解释您想要实现的功能的功能更为出色。 You could wrap any of the other answers in such a function too, however. 但是,你也可以在这样的函数中包装任何其他答案。

Boolean MoreThanOne(String str, Char c)
{
    return str.Count(x => x==c) > 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM