C#中的if语句判断字符串是否包含两个"hallo"

7

你是想要恰好2个,还是至少2个? - Adam Wright
8个回答

13

你可以使用正则表达式 :)

return Regex.Matches(hello, "hello").Count == 2;

如果计数为2,该模式将匹配字符串hello并返回true。


在我的情况下,这个方法不起作用是因为我要查找的字符串是一个点(“.”)。所以我将它从“hello”改为“\。”,然后它就正常工作了。谢谢。 - Word Rearranger

5

正则表达式。

if (Regex.IsMatch(hello,@"(.*hello.*){2,}"))

我想你的意思是“你好”,这将匹配至少有2个“你好”的字符串(不一定是恰好2个“你好”)。


+1 对于与计数正则表达式匹配的内容非常赞! - pjvds

2
public static class StringExtensions
{
    public static int Matches(this string text, string pattern)
    {
        int count = 0, i = 0;
        while ((i = text.IndexOf(pattern, i)) != -1)
        {
            i += pattern.Length;
            count++;
        }
        return count;
    }
}

class Program
{
    static void Main()
    {
        string s1 = "Sam's first name is Sam.";
        string s2 = "Dot Net Perls is about Dot Net";
        string s3 = "No duplicates here";
        string s4 = "aaaa";

        Console.WriteLine(s1.Matches("Sam"));  // 2
        Console.WriteLine(s1.Matches("cool")); // 0
        Console.WriteLine(s2.Matches("Dot"));  // 2
        Console.WriteLine(s2.Matches("Net"));  // 2
        Console.WriteLine(s3.Matches("here")); // 1
        Console.WriteLine(s3.Matches(" "));    // 2
        Console.WriteLine(s4.Matches("aa"));   // 2
    }
}

1

IndexOf

您可以使用IndexOf方法来获取某个字符串的索引。此方法有一个过载,它接受一个起始点,从此处开始查找。当未找到指定的字符串时,则返回-1

以下是一个例子,它说明了用法。

var theString = "hello hello bye hello";
int index = -1;
int helloCount = 0;

while((index = theString.IndexOf("hello", index+1)) != -1)
{
    helloCount++;
}

return helloCount==2;

正则表达式

另一种获取计数的方法是使用正则表达式:

return (Regex.Matches(hello, "hello").Count == 2);

1
你可以使用正则表达式,并检查Matches函数的结果长度。如果是两个,那么你就赢了。

1

new Regex("hello.*hello").IsMatch(hello)

或者

Regex.IsMatch(hello, "hello.*hello")


1
如果您使用正则表达式MatchCollection,您可以轻松地获得这个:
MatchCollection matches;

Regex reg = new Regex("hello"); 

matches = reg.Matches("hellohelloaklsdhas");
return (matches.Count == 2);

为什么需要使用matchposition - Vlad
@Vlad:你不需要这样做。这是从复制/粘贴中保留下来的。谢谢。 - Joel Etherton
或者你可以直接使用一行代码的静态方法。 - Ray
有无数种方法可以完成这个任务。我个人最喜欢@m0skit0的答案。我曾经想指出你的第一个答案使用了.Match而不是.Matches,但我觉得你最终会注意到它的 :) - Joel Etherton

1

IndexOf:

int FirstIndex = str.IndexOf("hello");
int SecondIndex = str.IndexOf("hello", FirstIndex + 1);
if(FirstIndex != -1 && SecondIndex != -1)
{
  //contains 2 or more hello
}
else
{
   //contains not
}

或者如果你想要精确的2:if(FirstIndex != -1 && SecondIndex != -1 && str.IndexOf("hello", SecondIndex) == -1)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接