Search code examples
c#arraystoupper

Make uppercase on the first letter of user input C#


I am trying to make an easy and clean solution for my code to recieve a name from input from user and printing it out with uppercase on the first letter only. I have tried for a long time but cannot come to a solution, I am now trying to make it by using an array and selecting the first letter but i get this error message "No overload for method 'ToUpper' takes 0 arguments"

** fn[0].ToUpper()** ?

IMAGE OF MY CODE

   static void Introduce()
    {
        Console.Write("Hi! What is your first name?");
        fn = Console.ReadLine();

        Console.Write("Hi! What is your last name?");
        ln = Console.ReadLine();


        name = fn[0].ToUpper() + " " + ln[0].ToUpper();

        Console.WriteLine(name);

    }

Would really appriciate any help!

Using .ToUpper and making it into an array and selecting the first letter [0] but with an error message.


Solution

  • Simple way with ToUpper:

    string firstName = char.ToUpper(fn[0]) + fn.Substring(1);
    string lastName = char.ToUpper(ln[0]) + ln.Substring(1);
    

    We first use char.ToUpper method to convert the first letter of the first name and last name to uppercase. And then we use Substring method to get the remaining part of the name, starting from index 1, and concatenate this 2 strings with + operator.

    You can also use string interpolation and ranges for string:

    string firstName = $"{char.ToUpper(fn[0])}{fn[1..]}";
    string lastName = $"{char.ToUpper(ln[0])}{ln[1..]}";