找不到错误。C++,字符串
Can't find a mistake. C++, strings
>我应该写一个程序,它只显示末尾有一个大写字母的单词。
例如:"somE wordS just RighT there" -> "somE wordS RighT">
但是我的代码有问题,我找不到错误。(对不起,这段代码,可能真的搞砸了(
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");
}
标准库已经为你在这里需要做的绝大多数事情提供了代码,所以只使用那里的内容可能更容易,而不是试图找出现有代码中的问题。
我可能会做这样的工作:
std::string silly_filter(std::string const &in) {
std::istringstream buff(in);
std::ostringstream out;
std::copy_if(std::istream_iterator<std::string>(buff),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(out, " "),
[](std::string const &s) {
return ::isupper((unsigned char)*s.crbegin());
});
return out.str();
}
据我所知
else if(isupper(textcopy[space-1])) {
sorted.append(textcopy, next, **space+1**);
}
空格 + 1 是要追加的字符串数。因此,如果 next=5,字符串将为 w,因此第二个参数应该是 'wordS' 的长度,即在这种情况下为 5,第二个参数继续增长。