两个空白之间的输出



我有这个字符串:System->ONDRASHEK: Nick aaasssddd není v žádné místnosti,我需要aaasssddd作为字符串的输出。每次输出都不一样。所以它必须从两个空白处获得。我尝试过substr或split,但我对C++的了解很差。

我发现这个代码:

   #include <string>
   #include <iostream>
   int main()
   {
    const std::string str = "System->ONDRASHEK: Nick aaasssddd není v žádné        místnosti";
    size_t pos = str.find(" ");
    if (pos == std::string::npos)
    return -1;
    pos = str.find(" ", pos + 1);
    if (pos == std::string::npos)
    return -1;
    std::cout << str.substr(pos, std::string::npos);
   }

但不是,我需要的。

我假设您想要给定字符串中的第三个单词。

您已经找到了第二个空格,但您的输出是从第二个空间到字符串末尾的子字符串。

相反,您需要找到第三个空格,并输出这两个空格之间的子字符串。

所以这里是修改。

#include <string>
#include <iostream>
int main()
{
    const std::string str = "System->ONDRASHEK: Nick aaasssddd není v žádné        místnosti";
    size_t pos = str.find(" ");
    size_t start;
    size_t end;
    if (pos == std::string::npos)
        return -1;
    pos = str.find(" ", pos + 1);
    if (pos == std::string::npos)
        return -1;
    start = pos + 1;
    pos = str.find(" ", pos + 1);
    if (pos == std::string::npos)
        return -1;
    end = pos;
    std::cout << str.substr(start, end - start) << std::endl;
}

请详细说明您的问题?你需要2个空格之间的子串吗?若我是真的,先找到第一个空格,然后打印字符串,直到找到另一个空格。您可以为使用字符

最新更新