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,827
  • 4
  • 40
  • 77
NoviceToDotNet
  • 10,387
  • 36
  • 112
  • 166

4 Answers4

22

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
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 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
13

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

string foo = "12121.23.2";
foo.Count(c => c == '.');
mensi
  • 9,580
  • 2
  • 34
  • 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
  • 300,895
  • 165
  • 679
  • 742
2
Boolean MoreThanOne(String str, Char c)
{
    return str.Count(x => x==c) > 1;
}
Rohit Sharma
  • 6,136
  • 3
  • 28
  • 47
  • 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