0

How could I check if a string contains exactly one char?

Example:

  • strings → check for 1 itrue
  • strings → check for 1 sfalse

I've tried to use Contains but it checks for 1 or more.

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144

1 Answers1

3

You could use this Linq query to solve it.

"strings".Where(c => c == 's').Count() == 1 // gives false
"strings".Where(c => c == 'i').Count() == 1 // gives true

Explanaition:

  • The Where method ask for a lamdba expression that checks if a char (variable c) of the given string (strings) is equal to respectively s or i and returns a list of chars that are equal to the condition.

  • The Count method counts the results of that list.

  • Finaly just check if the result is equal to one.

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
  • 4
    You can shorten with `"strings".Count(c => c == 's') == 1` – Tim Schmelter Jul 12 '18 at 09:22
  • 1
    This may do far more work than required if the string is millions of characters long and contains lots of repeats of the character. I'd usually advocate *against* counting if you don't actually want to know the count. Here, you don't need the count, you just need to classify the string by 0, 1 or *more than 1*. – Damien_The_Unbeliever Jul 12 '18 at 09:24
  • 3
    @Damien_The_Unbeliever: in that case he could use `bool moreThan1 = "strings".Where(c => c == 's').Skip(1).Any()` – Tim Schmelter Jul 12 '18 at 09:25
  • You could also do it the wrong way: Put in a try-catch "strings".Single(condition) and act whenever the catch is run or not. – Cleptus Jul 12 '18 at 09:49
  • @bradbury9: Yeah it's totaly wrong. If that was an answer -1 from me ;). – H. Pauwelyn Jul 12 '18 at 12:09