C#: how to get first char of a string?

Viewed 502725

Can the first char of a string be retrieved by doing the following?

MyString.ToCharArray[0]
15 Answers

Following example for getting first character from a string might help someone

string anyNameForString = "" + stringVariableName[0];

In C# 8 you can use ranges.

myString[0..Math.Min(myString.Length, 1)]

Add a ? after myString to handle null strings.

MyString.Remove(1, 2); also works

Answer to your question is NO.

Correct is MyString[position of character]. For your case MyString[0], 0 is the FIRST character of any string.

A character value is designated with ' (single quote), like this x character value is written as 'x'.

A string value is designated with " ( double quote), like this x string value is written as "x".

So Substring() method is also does not return a character, Substring() method returns a string!!!

A string is an array of characters, and last character must be '\0' (null) character. Thats the difference between character array and string ( which is an array of characters with last character as "end of string marker" '\0' null.

And also notice that 'x' IS NOT EQUAL to "x". Because "x" is actually 'x'+'\0'.

Maybe this will help. I'm using txtModel_Leave event then create method to detect the first char in main textbox.

private void txtMain_Leave(object sender, EventArgs e)
{
    detectFirstChar();
}

private void detectFirstChar() 
{
    string mystr = txtModel.Text;

    if (String.IsNullOrEmpty(txtModel.Text))
    {
        txtAwalan.Text = "";
    }
    else if (mystr.Substring(0, 1) == "F")
    {
        txtKategori.Text = "Finishing";               
    }
    else if((mystr.Substring(0, 1) == "H"))
    {
        txtKategori.Text = "Half";
    }
    else
    {
        txtKategori.Text = "NONE";
    }
}
Related