英文:
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()** ?
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.
英文:
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()** ?
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.
答案1
得分: 5
使用 ToUpper
方法的简单方式:
string firstName = char.ToUpper(fn[0]) + fn.Substring(1);
string lastName = char.ToUpper(ln[0]) + ln.Substring(1);
首先,我们使用 char.ToUpper
方法将名字的第一个字母转换为大写。然后,我们使用 Substring
方法从索引1开始获取名称的剩余部分,并使用 +
运算符连接这两个字符串。
您还可以使用字符串插值和范围来处理字符串:
string firstName = $"{char.ToUpper(fn[0])}{fn[1..]}";
string lastName = $"{char.ToUpper(ln[0])}{ln[1..]}";
<details>
<summary>英文:</summary>
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][1] and [ranges][2] for string:
string firstName = $"{char.ToUpper(fn[0])}{fn[1..]}";
string lastName = $"{char.ToUpper(ln[0])}{ln[1..]}";
[1]: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
[2]: https://learn.microsoft.com/ru-ru/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论