How to count how many uppercase characters exist in a string?

3

How to count how many uppercase characters exist in a string?

    
asked by anonymous 08.04.2015 / 23:32

2 answers

5

There are several ways to do this:

  • Using LINQ:

    var str = "Miguel Angelo";
    var contagem = str.Count(char.IsUpper);
    

    Note: You must import the LINQ namespace: using System.Linq;

  • Without using LINQ:

    var str = "Miguel Angelo";
    var contagem = 0;
    for (int itChar = 0; itChar < str.Length; itChar++)
        if (char.IsUpper(str[itChar]))
            contagem++;
    

Performance

I've done 4 performance tests:

  • Sm str - LINQ : test with 13 chars string using LINQ
  • Sm str - FOR : test with 13 chars string using for
  • Lg str - LINQ : string test of 13 * 1024 chars using LINQ
  • Lg str - FOR : test with a string of 13 * 1024 chars using for

Results:

Exec #1
    Sm str - LINQ     1.092µs (84ns por char)
    Sm str - FOR      0.462µs (36ns por char)
    Lg str - LINQ   609.931µs (46ns por char)
    Lg str - FOR    425.092µs (32ns por char)
Exec #2
    Sm str - LINQ     1.013µs (78ns por char)
    Sm str - FOR      0.436µs (34ns por char)
    Lg str - LINQ   606.826µs (46ns por char)
    Lg str - FOR    433.585µs (33ns por char)
Exec #3
    Sm str - LINQ     1.017µs (78ns por char)
    Sm str - FOR      0.459µs (35ns por char)
    Lg str - LINQ   616.975µs (46ns por char)
    Lg str - FOR    443.754µs (33ns por char)
Exec #4
    Sm str - LINQ     1.086µs (84ns por char)
    Sm str - FOR      0.458µs (35ns por char)
    Lg str - LINQ   683.890µs (51ns por char)
    Lg str - FOR    441.979µs (33ns por char)

Conclusion

You can only notice the difference when the string is greater than 100 million characters. It would be a ~ 100MB file in utf-8.

Then: Use the LINQ version in 99.99% of cases.

    
08.04.2015 / 23:38
1

You can do this using regular expression. Home Import the System.Text.RegularExpressions; namespace

 var str = "Paulo Costa";
 var count = Regex.Matches(str, "[A-Z]").Count;
    
10.04.2015 / 14:46