我对大写的每个单词中的第一个字母进行了以下操作,但它只对第一个单词起作用.有人能解释为什么吗?
static void Main(string[] args)
{
string s = "how u doin the dnt know about medri sho min shan ma baref shu";
string a = tocap(s);
Console.WriteLine(a);
}
public static string tocap(string s)
{
if (s.Length == 1) return s.ToUpper();
string s1;
string s2;
s1 = s.Substring(0, 1).ToUpper();
s2 = s.Substring(1).ToLower();
return s1+s2;
}
Run Code Online (Sandbox Code Playgroud)
Osc*_*Ryz 10
如果您真正了解自己在做什么,我想你会更好.
public static string tocap(string s)
{
// This says: "if s length is 1 then returned converted in upper case"
// for instance if s = "a" it will return "A". So far the function is ok.
if (s.Length == 1) return s.ToUpper();
string s1;
string s2;
// This says: "from my string I want the FIRST letter converted to upper case"
// So from an input like s = "oscar" you're doing this s1 = "O"
s1 = s.Substring(0, 1).ToUpper();
// finally here you're saying: "for the rest just give it to me all lower case"
// so for s= "oscar"; you're getting "scar" ...
s2 = s.Substring(1).ToLower();
// and then return "O" + "scar" that's why it only works for the first
// letter.
return s1+s2;
}
Run Code Online (Sandbox Code Playgroud)
现在你要做的就是改变你的算法(然后你的代码)来做你想做的事情
你可以在找到空格的部分"拆分"你的字符串,或者你可以找到每个字符,当你找到一个空格时,你知道下面的字母将是单词的开头不是吗?
试试这个算法-psudo代码
inside_space = false // this flag will tell us if we are inside
// a white space.
for each character in string do
if( character is white space ) then
inside_space = true // you're in an space...
// raise your flag.
else if( character is not white space AND
inside_space == true ) then
// this means you're not longer in a space
// ( thus the beginning of a word exactly what you want )
character = character.toUper() // convert the current
// char to upper case
inside_space = false; // turn the flag to false
// so the next won't be uc'ed
end
// Here you just add your letter to the string
// either white space, upercased letter or any other.
result = result + character
end // for
Run Code Online (Sandbox Code Playgroud)
想一想.
你会做你想做的事:
一个字母和一个字母
如果你在一个空间你放了一面旗帜,
当你不再在太空中,那么你就是在一个单词的开头,要采取的行动是将其转换为大写.
其余的你只需将这封信附加到结果中.
当你学习编程时,最好在论文中开始做"算法",一旦你知道它会做你想做的事情,依次将它传递给编程语言.