为什么在使用tocap()函数时只有第一个单词大写?

我对大写的每个单词中的第一个字母做了以下操作,但它只对第一个单词起作用。 有人可以解释原因吗?

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; } 

如果您真正了解自己在做什么,我猜你会更好。

  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; } 

现在你要做的就是改变你的算法(然后你的代码)来做你想做的事情

你可以在找到空格的部分“拆分”你的字符串,或者你可以找到每个字符,当你找到一个空格时,你知道下面的字母将是单词的开头不是吗?

试试这个算法 – 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 

想一想。

你会做你想做的事:

  • 一个字母和一个字母

  • 如果你在一个空间你放了一面旗帜,

  • 如果你不再在太空中,那么你就是在一个单词的开头,要采取的行动是将其转换为大写。

  • 其余的只需将字母附加到结果中即可。

当你学习编程时,最好在论文中开始做“算法”,一旦你知道它会做你想做的事情,依次将它传递给编程语言。

既然没有教授会接受这个解决方案,我觉得很好,任何人都可以通过Google搜索,知道你可以使用ToTitleCase

学会喜欢string.split()方法。

还有更多的帮助,我会觉得很脏。

尝试使用:

System.Globalization.TextInfo.ToTitleCase

你需要以某种方式标记你的初始字符串。 你现在甚至都没有看过整个事物的第一个角色。

使用string.Split(”)将句子分解成一堆单词而不是使用你需要的代码来大写每个单词…然后将它们全部重新组合在一起。