首页 > 解决方案 > C++ - 在子字符串上执行的查找函数不起作用

问题描述

我确实遇到了一个算法问题,我想用它来将命令行拆分为几个子字符串。例如,字符串"Hello World -n filename"应该被分割成"Hello" "World"and "-n filename"

这是我的整个代码示例:

string hello = "Hello World -n filename";
uint64_t startIndex = 0;
uint64_t endIndex = hello.length() - 1;

while(startIndex < endIndex) {
    uint64_t nextWhiteSpaceIndex;
    string value;

    if(hello.at(startIndex) != '-') {

        nextWhiteSpaceIndex = hello.substr(startIndex).find(" ");
        value = hello.substr(startIndex, nextWhiteSpaceIndex);
        cout << value << endl;

    } else {

        nextWhiteSpaceIndex = hello.substr(hello.substr(startIndex).find(" ")).find(" ");
        value = hello.substr(startIndex, nextWhiteSpaceIndex);
        cout << value << endl;

    }
    startIndex = nextWhiteSpaceIndex + 1;
}

我确实有这个命令的问题:

nextWhiteSpaceIndex = hello.substr(startIndex).find(" ");

这被放置在while循环中,看起来像......

.substr(startIndex)

...部分被完全忽略。第一个循环运行正常,但在第二个/以下 nextWhiteSpaceIndex 没有得到正确的下一个索引分配。它总是打印"Hello" "World" "World" "World" "World"并继续打印"World"

你们有提示吗,为什么这不起作用?在通过网络进行研究期间,我找不到合适的解释。

标签: c++c++11

解决方案


你不能做类似的事情吗

#include <sstream>
#include <stdio>
#include <vector>

using namespace std;

int main ()
{
    string hello = "Hello World -n filename";

    stringstream ss (hello);
    vector<string> v;
    string s, t;

    while (ss >> s)
    {
        if (s[0] == '-')
        {   
            ss >> t;
            v.push_back (s + " " + t); 
        }   
        else
            v.push_back (s);
    }

    for (auto i : v)
        clog << i << endl;

    return 0;
}

生产

$ ./a.out
Hello
World
-n filename

推荐阅读