【发布时间】:2017-03-21 16:18:46
【问题描述】:
我应该写一个程序,它只显示最后有大写字母的单词。
例如: “一些词就在那儿”->“一些词就在那儿”
但是我的代码有问题,我找不到错误。 (对不起这段代码,它可能真的搞砸了)
string LastUpperSymbol(string text) {
int i = 0, space, next, sortEl = 0;
string textcopy = text;
int size = textcopy.size();
string sorted;
string alph = "abcdefghijklmnopqrstuvwxyz ";
if (textcopy[0] != alph[26]) {
space = text.find(" ");
if(isupper(textcopy[space-1])) {
sorted.append(textcopy, 0, space+1);
}
while(space < textcopy.size()) {
next = space+1;
space = text.find(" ", next);
if(space == -1) {
if(isupper(textcopy[size])) {
sorted.append(textcopy, next, textcopy[size]);
}
break;
}
else if(isupper(textcopy[space-1])) {
sorted.append(textcopy, next, space+1);
}
}
}
else {
//something
}
cout << sorted << endl;
return text;
}
int main() {
string text = "somE wordS just RighT there";
cout << LastUpperSymbol(text);
system("PAUSE");
}
【问题讨论】:
-
您的字符串实现很可能有一个调试标志,您可以使用它来启用诸如越界检查之类的东西,尽管我可能会考虑其他库部分而不是
string。如果不出意外,可以通过使用at而不是[]来大声地越界。您也可以尝试使用消毒工具。 -
我的建议是学习如何使用调试器单步执行代码,查看每一步的变量。
-
始终检查
find的结果以确保它不是std::string::npos。 -
@WhozCraig 在 C++11 及更高版本中
textcopy[textcopy.size()]是完全合法的,并为您提供空终止符 (charT{})。你不能修改它,但看看它就可以了。 -
@NathanOliver 这是真的。六年了,我还是习惯了。谢谢你让我诚实。不过,
textcopy[size]对append的影响是一个奇怪的 count,你不觉得吗?