我正在做一项作业,它希望我让用户输入一个没有空格的字符串,并通过以大写字母开头来识别每个单词,因此“IAmName”将转换为“I Am Name”。我想我已经完成了那部分,我的问题是最后一步,即在标签中显示新字符串,这是我目前的代码:
private string ConvertText()
{
string str = inputTextBox.Text;
if (str.Contains(" "))
{
MessageBox.Show("No spaces allowed");
}
string newstring = outputLabel.Text;
for (int i = 0; i < str.Length; i++)
{
if (char.IsUpper(str[i]))
newstring += " ";
newstring += str[i].ToString();
}
return newstring;
}
如有任何帮助,我们将不胜感激。
请您参考如下方法:
反过来做:
outputLabel.Text = ConvertText(); // Or any other label that should display it
我不确定为什么你的代码中有这个 (string newstring = outputLabel.Text;)。您没有使用它,只是覆盖它。
您可能还想使用 StringBuilder 在循环中进行连接,这样效率更高。
并且这段代码可能应该添加一个return;
if (str.Contains(" "))
{
MessageBox.Show("No spaces allowed");
return; // Return so it stops executing this method
}
