how to get every element of a string?

For example,

string s = "12";

then, how can I get the last element "2" of s

For array, we can access each element by the index, however, I do not know how to deal with a string..

Any suggestion

Thanks!




Answer this question

how to get every element of a string?

  • h1

    What He Said!

    Also, if you want to get at an individual char in a string for any reason, just use the index operator:

    string str = "ABCDEFG";
    int index = 2;
    char ch = str[index];


  • Leonard Lee

    I find one way,

    string p = "";
    for (int j = 0; j < (i - 1); j++)
    {
    p = p + a[j];
    }

    So that I can get rid of the last element of the original string

    Is there any other method to realize this



  • Jay_Vora_b4843e

    Thank you Jeremy!

    I will try your method..

    I searched just now, and find a way:

    string s = "123";
    string a = " ";
    IEnumerator Enum = s.GetEnumerator();
    while (Enum.MoveNext())
    {
    a = Enum.Current.ToString();
    }

    I will get a="3" by above method, is it OK

    Well, my purpose is to get the last element of the a string...

    Then, what should I do to subtract an element of string s After I know the last element of s is "3", I should get rid of this element and to store "12" to string s..

    It seems we can add two strings together just by "+", however, we can not subtract two strings by just "-", any suggestion

    Thank you!



  • fleo

    I don't really understand what you're trying to do...just remove the last character from a string

    Then you can just do:
    if (s.Length > 0)
    s = s.Substring(0, s.Length - 1);

  • jtalbotfdr

    You could use Substring() to get a single-char string. You could also use ToCharArray() to get an array of chars.

  • user11

    Yeah, I can access the last element of a string by ToCharArray();

    string s = "23456";
    char[] a = s.ToCharArray();
    int i = (int)a.Length;
    a[i - 1].ToString();

    Then, how can I get the modified string s = "2345"

    To convert a CharArray to a string, is there any method

    I will search around..



  • how to get every element of a string?