C# c“如果字符串包含2”;哈罗“;
可能重复:C# c“如果字符串包含2”;哈罗“;,c#,string,C#,String,可能重复: 我想检查一个字符串是否包含两个内容 String hello = "hellohelloaklsdhas"; if hello.Contains(*hello 2 Times*); -> True 如何解决此问题?您可以使用正则表达式,并检查匹配结果函数的长度。如果是两个你赢。新的正则表达式(“hello.*hello”)。IsMatch(hello) 或 Regex.IsMatch(hello,“hello.*hello”)正则表达式 if (Regex.IsMatch
我想检查一个字符串是否包含两个内容
String hello = "hellohelloaklsdhas";
if hello.Contains(*hello 2 Times*); -> True
如何解决此问题?您可以使用正则表达式,并检查匹配结果函数的长度。如果是两个你赢。
新的正则表达式(“hello.*hello”)。IsMatch(hello)
或
Regex.IsMatch(hello,“hello.*hello”)
正则表达式
if (Regex.IsMatch(hello,@"(.*hello.*){2,}"))
我猜您的意思是“hello”,这将匹配一个至少有2个“hello”的字符串(不完全是2个“hello”)您可以使用正则表达式:)
这与模式“hello”的字符串
hello
匹配,如果计数为2,则返回true。如果使用正则表达式MatchCollection,则可以轻松获得:
MatchCollection matches;
Regex reg = new Regex("hello");
matches = reg.Matches("hellohelloaklsdhas");
return (matches.Count == 2);
索引
您可以使用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);
索引of:
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:
如果(FirstIndex!=-1&&SecondIndex!=-1&&str.IndexOf(“你好,SecondIndex)=-1)
你想要正好2,或者至少2?+1来匹配一个计数正则表达式:-)thx作为答案,我明天会试试。你为什么需要匹配位置
?@Vlad:你不需要。这是复制/粘贴造成的延期。谢谢。或者你可以只使用一行静态方法。有很多方法可以完成这个任务。我个人最喜欢@m0skit0的答案。我很想指出,您的第一个答案使用了.Match而不是.Matches,但我想您最终会理解:)在我的情况下,这不起作用,因为我要查找的字符串是一个点(“.”)。因此,我将它改为“\”,而不是“你好”,效果很好。非常感谢。
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
}
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
}
}