【问题标题】:Can't find a mistake. C++, strings找不到错误。 C++,字符串
【发布时间】: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,你不觉得吗?

标签: c++ string uppercase


【解决方案1】:

标准库已经为您在这里需要做的绝大多数事情提供了代码,因此使用现有代码可能更容易,而不是试图找出现有代码中的问题。

我可能会做这样的工作:

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();
}

【讨论】:

    【解决方案2】:

    据我所知

    else if(isupper(textcopy[space-1])) { sorted.append(textcopy, next, **space+1**); }

    空格 + 1 是要追加的字符串数。因此,如果 next=5,则字符串将为 w,因此第二个参数应该是 'wordS' 的长度,即 5 在这种情况下,第二个参数会继续增长。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多