Tuesday 19 November 2013

How to loop through characters in a string?

This can be done using a foreach loop.

Following example finds the count of letters in a given string.

int count = 0;

string str = "Welcome to C#!";

foreach(char c in str) {
  if(char.IsLetter(c)) {
    count++;
  }
}

Cosole.WriteLine(count.ToString());
There are additional static methods on char that will tell you if the character in question is punctuation, a digit, etc.

No comments:

Post a Comment