10

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.

Anders Forsgren
  • 10,408
  • 4
  • 37
  • 74
NoviceToDotNet
  • 9,889
  • 32
  • 106
  • 163

4 Answers4

21

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)) {
    ...
}
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
  • This fails if the character is not present at all, as both indices evaluate to -1. – Drew Noakes Jul 06 '13 at 11:54
  • 4
    @DrewNoakes Why? If the character is not present at all, both functions return `-1`, so `!=` evaluates to `false`. You need two or more characters in there: for zero or one character, first and last indexes are the same (the actual index, or `-1`). – Sergey Kalinichenko Jul 06 '13 at 12:12
12

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

string foo = "12121.23.2";
foo.Count(c => c == '.');
mensi
  • 9,325
  • 2
  • 32
  • 43
6

If performance matters, write it 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;
}

In this way, you only make one pass through the string's contents, and you bail out as early as possible. In the worst case you visit all characters only once. In @dasblinkenlight's answer, you would visit all characters twice, and in @mensi's answer, you have to count all instances, even though once you have two you can stop the calculation. Further, using the Count extension method involves using an Enumerable<char> which will run more slowly than directly accessing the characters at specific indices.

Then you may 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 think it's nicer to have a function that explains exactly what you're trying to achieve. You could wrap any of the other answers in such a function too, however.

Drew Noakes
  • 284,599
  • 158
  • 653
  • 723
2
Boolean MoreThanOne(String str, Char c)
{
    return str.Count(x => x==c) > 1;
}
Rohit Sharma
  • 5,600
  • 3
  • 27
  • 42
  • string and char cannot be having equal sign within them –  Nov 21 '17 at 10:18
  • Yes and I am not using it either in my answer, please understand what I am doing, if you don't understand then try running and see for yourself if it works or not. – Rohit Sharma Nov 21 '17 at 10:26