0

I've built a string builder to add spaces into text if it is capital. The sentence entered would look like this : "ThisIsASentence." Since it starts with a capital, the string builder would modify the sentence to look like this: " This Is A Sentence."

My problem is, If I were to have a sentence like "thisIsASentence." the string builder will separate the sentence like normal : " this Is A Sentence."

Still both have a space in front of the first character.

When the sentence runs through this line:

result = result.Substring(1, 1).ToUpper() + result.Substring(2).ToLower();

If the first letter entered was lowercase, it gets cut off and the second letter becomes uppercase.

The line was meant to keep the first letter entered capitalized and set the rest lowercase.

Adding a trim statement before running that line changes nothing with the output.

Here is my overall code right now:

        private void btnChange_Click(object sender, EventArgs e)
    {   
        // New string named sentence, assigning the text input to sentence.
        string sentence;
        sentence = txtSentence.Text;

        // String builder to let us modify string
        StringBuilder sentenceSB = new StringBuilder();

        /*
         *  For every character in the string "sentence" if the character is uppercase,
         *  add a space before the letter,
         *  if it isn't, add nothing.
         */
        foreach (char c in sentence)
        {
            if (char.IsUpper(c))
            {
                sentenceSB.Append(" ");
            }
            sentenceSB.Append(c);
        }


        // Store the edited sentence into the "result" string
        string result = sentenceSB.ToString();

        // Starting at the 2nd spot and going 1, makes the first character capitalized
        // Starting at position 3 and going to end change them to lower case.
        result = result.Substring(1, 1).ToUpper() + result.Substring(2).ToLower();

        // set the label text to equal "result" and set it visible.
        lblChanged.Text = result.ToString();
        lblChanged.Visible = true;
4

2 回答 2

1

当您使用“thisIsASentence”运行代码时,在 foreach 循环之后,结果将是“this Is A Sentence”,因为它不会在开头插入空格。

然后你的下一行,将采用索引 1 处的字符(即此处的 'h'),将其设为大写,然后附加字符串的其余部分,从而生成“His Is A Sentence”

要解决此问题,您可以result = result.Trim()在循环之后执行,然后从索引 0 开始,制作下一行result = result.Substring(0, 1).ToUpper() + result.Substring(1).ToLower();

于 2013-10-03T17:09:51.010 回答
0

使用result.SubString(1,1),您假设输入的第一个字母始终大写,因此您将始终在字符串的开头添加一个空格。您已经看到情况并非如此。

所以我基本上看到了两种选择:

将该行包装在一个 if 块中,该块在替换之前检查空格;

如果您的规范允许,请将您输入的第一个字母大写。

于 2013-10-03T17:12:40.637 回答