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

时间:2009-01-06 18:46:03

标签: c# string

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

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

6 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分: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;
    }

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

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

尝试此算法-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

想一想。

你会做你想做的事:

  • 逐字逐句地和

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

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

  • 其余的你只需将信附加到结果中。

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

答案 2 :(得分:9)

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

除此之外还有任何帮助,我会觉得很脏。

答案 3 :(得分:4)

答案 4 :(得分:1)

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

答案 5 :(得分:1)

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