CmplDev
CmplDev

Reputation: 37

Checking for a character being in a string multiple times

Ran into a little problem, I want to check if a certain character is in a string multiple times. This is the string:

string str01 = "?????????? ??????????, ??????????, ???????? !!!";

Now I want to check if the character "?" is in the string at least 10 times. I tried using an array but the spaces would trick that. Thanks in advance!

Upvotes: 3

Views: 1430

Answers (5)

wischi
wischi

Reputation: 676

For very (very) long strings you should not use Enumerable.Count solutions because they evaluate the entire string (even if the first 10 characters are already question marks)

Alternative
Create an extension class which shortcuts the count if possible:

public static class AtLeastExtension
{
    public static bool AtLeast<T>(this IEnumerable<T> enumerable, T e, int Max)
    { 
        if (enumerable == null) throw new ArgumentNullException(nameof(enumerable));
        if (Max < 0) throw new ArgumentOutOfRangeException(nameof(Max));
        if (Max == 0) return true;

        int cnt = 0;
        foreach (var item in enumerable)
            if (object.Equals(item, e))
                if (++cnt >= Max) return true;
        return false;
    }
}

Usage

var result = str01.AtLeast('?', 10);

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

If you want just assure that ? appears at least 10 times you can use Linq:

  string source = "?????????? ??????????, ??????????, ???????? !!!";
  int repeatAtLeast = 10;

  bool appears = source
    .Where(c => c == '?')
    .Skip(repeatAtLeast - 1)
    .Any(); 

for long strings Where + Skip + Any can be more efficient than Count(c => c == '?'): we stop when 10th '?' has been found, and do not need to scan the entire string.

Upvotes: 0

princeofmince
princeofmince

Reputation: 1

If you wanted to keep your array approach, you could use the string.Replace() method to take out the whitespace and commas:

str01 = str01.Replace(" ", "");
str01 = str01.Replace(",", "");

But the other solutions using LINQ are probably better.

Upvotes: 0

Charles Mager
Charles Mager

Reputation: 26223

Helpfully, string implements IEnumerable<char>, so you can use some LINQ:

var result = str01.Count(x => x == '?') > 10;

See this fiddle.

Upvotes: 3

Almir Vuk
Almir Vuk

Reputation: 3173

You can try with LINQ like this:

int count = source.Count(f => f == '?');

And than you can compare count variable with value that you want.

Upvotes: 0

Related Questions