How do I iterate each character in a string?

Category: System, viewed: 349 time(s).

In this example we show how to iterate each character in a string variable. First we iterate the string using the foreach loop statement and the second way is using the standard for loop. In the loop we just add simple checking whether the string is a letter or a digit and if it is in uppercase or lowercase form.

using System;

namespace Kodecsharp.Example.System
{
    class IteratingString
    {
        public static void Main(string[] args)
        {
            string text = "1a2B3C4d5e6f7G8H9I0Z";

            //
            // Iterating string using foreach loop.
            //
            foreach (char c in text)
            {
                if (Char.IsDigit(c))
                {
                    Console.WriteLine(c + " is digit");
                } else if (Char.IsLetter(c))
                {
                    Console.WriteLine(c + " is letter");
                }
            }

            //
            // Iterating string using for loop.
            //
            for (int i = 0; i < text.Length; i++)
            {
                if (Char.IsUpper(text[i]))
                {
                    Console.WriteLine(text[i] + " is uppercase");
                } else if (Char.IsLower(text[i]))
                {
                    Console.WriteLine(text[i] + " is lowercase");
                }
            }

            //
            // Print the string in reverse order.
            //
            for (int i = text.Length - 1; i >= 0; i--)
            {
                Console.Write(text[i]);
            }

            Console.ReadLine();
        }
    }
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Statistics

Locations of visitors to this page