C # if String contains 2 "hallo"

Possible duplicate:
How would you count the occurrences of a string in a string (C #)?

I want to check if a string contains String 2 stuff.

String hello = "hellohelloaklsdhas"; if hello.Contains(*hello 2 Times*); -> True 

How can i solve this?

+4
source share
8 answers

You can use regex :)

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

This matches the hello string for the "hello" pattern and returns true if the counter is 2.

+10
source

Regular expressions.

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

I assume you meant “hi” and that would match a line with at least 2 “hi” (not exactly 2 “hi”)

+5
source
 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 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 } } 
+2
source

You can use the regular expression and check the length of the result of the Match function. If you win two.

+1
source

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

or

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

+1
source

If you use the MatchCollection regular expression, you can easily do this:

 MatchCollection matches; Regex reg = new Regex("hello"); matches = reg.Matches("hellohelloaklsdhas"); return (matches.Count == 2); 
+1
source

Indexoff

You can use the IndexOf method to get the index of a specific row. This method has an overload that takes a starting point where to look for it. When the specified string is not found, -1 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; 

Regex

Another way to get a counter is to use Regex:

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

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)

+1
source

Source: https://habr.com/ru/post/1380225/


All Articles