Access the character in a string

To access the characters in a string by index we use the indexer of string type.


using System;

class Sample
{
    public static void Main()
    {

      string s = "java2s.com";
      Console.WriteLine(s[2]);
    }
}

The output:


v

string type implements the IEnumerable<char> interface, therefore it is handy to access each character in a string with foreach loop.


using System;

class Sample
{
    public static void Main()
    {

        string s = "java2s.com";
        foreach (char ch in s)
        {
            Console.WriteLine(ch);

        }
    }
}

The output:


j
a
v
a
2
s
.
c
o
m
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.