Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 832
NoviceToDotNet Avatar asked Jul 06 '13 11:07

NoviceToDotNet


People also ask

How do I check if a string contains a substring more than once?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do I check if a string contains more than one character in Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .

How do you check if a specific character occurs in a string?

You can use string. indexOf('a') . If the char a is present in string : it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

How do you check if a string contains all the characters of another string?

replace(str2[i], ''); if(str11 === str1){ return false; } str1 = str11; } // If all the characters have been found in the second string, then return true.


2 Answers

You can compare IndexOf to LastIndexOf to check if there is more than one specific character in a string without explicit counting:

var s = "12121.23.2";
var ch = '.';
if (s.IndexOf(ch) != s.LastIndexOf(ch)) {
    ...
}
like image 112
Sergey Kalinichenko Avatar answered Sep 20 '22 13:09

Sergey Kalinichenko


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

string foo = "12121.23.2";
foo.Count(c => c == '.');
like image 26
mensi Avatar answered Sep 21 '22 13:09

mensi