我想检查一个字符串是否包含2个内容...
可能是重复的问题:
如何在字符串内计数字符串的出现次数(C#)?
String hello = "hellohelloaklsdhas";
if hello.Contains(*hello 2 Times*); -> True
我该如何解决这个问题?
我想检查一个字符串是否包含2个内容...
可能是重复的问题:
如何在字符串内计数字符串的出现次数(C#)?
String hello = "hellohelloaklsdhas";
if hello.Contains(*hello 2 Times*); -> True
你可以使用正则表达式 :)
return Regex.Matches(hello, "hello").Count == 2;
如果计数为2,该模式将匹配字符串hello
并返回true。
正则表达式。
if (Regex.IsMatch(hello,@"(.*hello.*){2,}"))
我想你的意思是“你好”,这将匹配至少有2个“你好”的字符串(不一定是恰好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
}
}
您可以使用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);
new Regex("hello.*hello").IsMatch(hello)
或者
Regex.IsMatch(hello, "hello.*hello")
MatchCollection matches;
Regex reg = new Regex("hello");
matches = reg.Matches("hellohelloaklsdhas");
return (matches.Count == 2);
matchposition
? - VladIndexOf:
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)