-3

I would like to do a check to count the number of times a ":" appears in a string. Already I have this code:

        if (string.IsNullOrWhiteSpace(entryTrimmed) ||
            isAvailable != null ||
            entryTrimmed.StartsWith("::") ||
            entryTrimmed.EndsWith("::")) ||
            entryTrimmed.
        {
            OK_Button.IsEnabled = false;
            return;
        }

Is there a simple way that I could also include where there are more than three ":"?

Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

1

You can use count method

var colonCount = entryTrimmed.Count(e => e == ':')
Aakash
  • 155
  • 1
  • 3
  • 11
1

Simple linq's count:

    if (string.IsNullOrWhiteSpace(entryTrimmed) ||
        isAvailable != null ||
        entryTrimmed.StartsWith("::") ||
        entryTrimmed.EndsWith("::")) ||
        entryTrimmed.Count(c => c == ':') > 3 // there are more than three ":"
    {
        OK_Button.IsEnabled = false;
        return;
    }

If you don't want to use linq, you can use Replace and Length:

    if (string.IsNullOrWhiteSpace(entryTrimmed) ||
        isAvailable != null ||
        entryTrimmed.StartsWith("::") ||
        entryTrimmed.EndsWith("::")) ||
        entryTrimmed.entryTrimmed.Length - entryTrimmed.Replace(":", "").Length > 3 // there are more than three ":"
    {
        OK_Button.IsEnabled = false;
        return;
    }
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121