【发布时间】:2013-10-03 16:59:57
【问题描述】:
我已经构建了一个字符串生成器,如果它是大写的,则可以在文本中添加空格。输入的句子如下所示:“ThisIsASentence”。由于它以大写字母开头,字符串生成器会将句子修改为如下所示:“This Is A Sentence”。
我的问题是,如果我有一个像“thisIsASentence”这样的句子。字符串生成器会像平常一样分隔句子:“this Is A Sentence.”
在第一个字符前面仍然有一个空格。
当句子贯穿这一行时:
result = result.Substring(1, 1).ToUpper() + result.Substring(2).ToLower();
如果输入的第一个字母是小写的,它会被截断,第二个字母变成大写。
该行是为了保持输入的第一个字母大写,其余的设置为小写。
在运行该行之前添加一条修剪语句不会改变输出。
这是我现在的整体代码:
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;
【问题讨论】: