How to determine if a string contains more than one instance of a specific character?

I want to check if a string contains more than one character in a string? If I have line 12121.23.2, so I want to check if it contains several. in line.

+6
source share
5 answers

You can compare IndexOf with LastIndexOf to check if more than one particular character exists in a string without an explicit count:

 var s = "12121.23.2"; var ch = '.'; if (s.IndexOf(ch) != s.LastIndexOf(ch)) { ... } 
+14
source

You can easily count the number of occurrences of a character with LINQ:

 string foo = "12121.23.2"; foo.Count(c => c == '.'); 
+7
source

If performance matters, write yourself:

 public static bool ContainsDuplicateCharacter(this string s, char c) { bool seenFirst = false; for (int i = 0; i < s.Length; i++) { if (s[i] != c) continue; if (seenFirst) return true; seenFirst = true; } return false; } 

This way you only make one pass through the contents of the string, and you exit as soon as possible. In the worst case scenario, you visit all the characters only once. In @ dasblinkenlight's answer, you visited all the characters twice, and in @mensi's answer you should count all instances, even if you have two, you can stop the calculation. In addition, using the Count extension method involves using an Enumerable<char> , which will work slower than direct access to characters with specific indices.

Then you can write:

 string s = "12121.23.2"; Debug.Assert(s.ContainsDuplicateCharacter('.')); Debug.Assert(s.ContainsDuplicateCharacter('1')); Debug.Assert(s.ContainsDuplicateCharacter('2')); Debug.Assert(!s.ContainsDuplicateCharacter('3')); Debug.Assert(!s.ContainsDuplicateCharacter('Z')); 

I also find it better to have a function that accurately explains what you are trying to achieve. However, you can wrap any of the other answers in such a function.

+6
source
 Boolean MoreThanOne(String str, Char c) { return str.Count(x => x==c) > 1; } 
+2
source

Dasblinkenlight's answer is almost correct. You also need to check if the string really contains ".". in that. Since both IndexOf () and LastIndexOf () return -1 in the absence of '.' char in the string.

Here is a corrected example:

 var s = "12121.23.2"; var ch = '.'; if ((s.IndexOf(ch) >= 0) && (s.IndexOf(ch) != s.LastIndexOf(ch))) { ... } 

EDIT: wrong, no need to check if the string really contains ".".

0
source

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


All Articles