版权声明:本文为博主原创文章,采用“署名-非商业性使用-禁止演绎 2.5 中国大陆”授权。欢迎转载,但请注明作者姓名和文章出处。 https://blog.csdn.net/njit_77/article/details/79735201
Challenge
Using the C# language, have the function
LetterCapitalize(str) take the
str parameter being passed and capitalize the first letter of each word. Words will be separated by only one space.
Sample Test Cases
Input:"hello world"
Output:"Hello World"
Input:"i ran there"
Output:"I Ran There"
Letter Capitalize算法 大写字符串中的每个单词首字母,单词用空格隔开
public static string LetterCapitalize(string str)
{
char[] chArray = str.ToArray();
int length = chArray.Length;
char ch = '\0';
bool IsFirstLetter = true;
for (int i = 0; i < length; i++)
{
ch = chArray[i];
if ((ch >= 'a' && ch <= 'z'))
{
if (IsFirstLetter)
{
ch = (char)(ch - 32);
IsFirstLetter = false;
}
}
else if ((ch >= 'A' && ch <= 'Z'))
{
if (IsFirstLetter)
{
IsFirstLetter = false;
}
}
else if (ch == ' ')
{
IsFirstLetter = true;
}
chArray[i] = ch;
}
str = new string(chArray);
return str;
}