Search code examples
c#stringslice

Getting the letters from one index to another in a string using C#


I've been trying to make a small function which makes the first letter of a word uppercase, and the rest lowercase. I've found that I need to get the letters from index 1 to the length of the string, but I haven't found a way to do it.

Here's an example:

string GetName(string name)
{
    string newName = name[0].ToUpper();
    // join newName with the rest which was converted to lowercase
    return newName;
}

I have tried to find a solution online, but I have only found a way to get a the rest of a string after a letter. (note: I have realised a way to do this without a function like this, but I would still like this for future projects)


Solution

  • Using traditional string methods:

    var newName = char.ToUpper(name[0]) + name.Substring(1).ToLower();
    

    or

    var newName = name.Substring(0,1).ToUpper() + name.Substring(1).ToLower();
    

    With the proposed slicer syntax:

    var newName = name[0..1].ToUpper() + name[1..].ToLower();