Possible Duplicate:
How would you count occurences of a string within a string (C#)?
I want to check if a String contains 2 things..
String hello = "hellohelloaklsdhas";
if hello.Contains(*hello 2 Times*); -> True
How can I solve this?
Possible Duplicate:
How would you count occurences of a string within a string (C#)?
I want to check if a String contains 2 things..
String hello = "hellohelloaklsdhas";
if hello.Contains(*hello 2 Times*); -> True
How can I solve this?
You could use a regex :)
return Regex.Matches(hello, "hello").Count == 2;
This matches the string hello
for the pattern "hello"
and returns true if the count is 2.
Regular expressions.
if (Regex.IsMatch(hello,@"(.*hello.*){2,}"))
I guess you meant "hello", and this will match a string with at least 2 "hello" (not exactly 2 "hello")
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
}
}
You can use a regex, and check the length of the result of Matches function. If it's two you win.
new Regex("hello.*hello").IsMatch(hello)
or
Regex.IsMatch(hello, "hello.*hello")
If you use a regular expression MatchCollection you can get this easily:
MatchCollection matches;
Regex reg = new Regex("hello");
matches = reg.Matches("hellohelloaklsdhas");
return (matches.Count == 2);
You can use the IndexOf
method to get the index of a certain string. This method has an overload that accepts a starting point, from where to look. When the specified string is not found, -1
is returned.
Here is an example that should speak for itself.
var theString = "hello hello bye hello";
int index = -1;
int helloCount = 0;
while((index = theString.IndexOf("hello", index+1)) != -1)
{
helloCount++;
}
return helloCount==2;
Another way to get the count is to use Regex:
return (Regex.Matches(hello, "hello").Count == 2);
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
}
or if you want exactly 2: if(FirstIndex != -1 && SecondIndex != -1 && str.IndexOf("hello", SecondIndex) == -1)