我是编程新手,我的算法课中有一个项目。我们要做的就是决定一个问题并解决它。除了 string、char 和 WriteLine 之外,我们还没有学到太多东西。我们确实添加了一些内容,您很快就会看到!
我决定要解决这个问题:用户插入一个单词,无论多长,程序都会自动将第一个字母变成大写字母。到目前为止,这就是我所拥有的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
start:
Console.WriteLine("Please enter a word below:");
Console.WriteLine("");
string str = Console.ReadLine();
char char1;
if (str[0] >= 97)
{
char1 = (char)(str[0] - 32);
}
else
{
char1 = (char)(str[0] + 32);
}
char char2 = (char)(str[1]);
char char3 = (char)(str[2]);
char char4 = (char)(str[3]);
char char5 = (char)(str[4]);
Console.WriteLine("");
Console.Write(char1);
Console.Write(char2);
Console.Write(char3);
Console.Write(char4);
Console.WriteLine(char5);
goto start;
}
}
}
该代码的问题是任何少于 5 个字母的单词都会导致程序崩溃。任何超过 5 个字母的内容都会在第五个字母处被剪切...有人告诉我使用数组应该可以解决这个问题。鉴于我在这方面完全是新手,我需要将其分解并尽可能简单地讲述!
任何帮助使其正常工作将不胜感激。
谢谢:)
最佳答案
Console.WriteLine("Enter a word:");
string str = Console.ReadLine();
Console.WriteLine(str[0].ToString().ToUpper() + str.Substring(1));
这会起作用。
或者...如果您需要遍历整个字符串并找到第一个实际的字母字符,您可以执行以下操作:
Console.WriteLine("Please enter a word:");
string s = Console.ReadLine();
bool found = false;
char[] chars = new char[s.Length];
for (int i = 0; i < s.Length; i++)
{
if (Char.IsLetter(s[i]) && !found)
{
chars[i] = s[i].ToString().ToUpper()[0];
found = true;
}
else
{
chars[i] = s[i];
}
}
s = new String(chars);
Console.WriteLine(s);
关于C#:如何使用数组、字符和字符串?需要清理的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13077997/