首页 > 解决方案 > 为什么我的字符串函数不返回任何内容?

问题描述

该函数要么不返回任何内容,要么返回一个空字符串。我试图-e在字符串中的文本之后的下一个序列之前擦除所有内容。例如,test -e test/file/path应该返回test/file/path不带空格的-e. 但是,当函数不返回任何内容或返回空字符串时。我找不到我的功能有什么问题,请帮忙!

#include <iostream>
using namespace std;

string fileparse(string str) {
    int i;

    for (i = 0; i < str.size(); i++)
        if (str[i] == '-')
            i += 2; //to account for the space after 'e'
    str.erase(str.begin(), str.begin()+i);
    return str;
}

int main()
{

    string str = "test -e test/file/path";
    string vars = fileparse(str);
    cout << vars << endl; //blank
    return 0;
}

标签: c++stringfunctionparsing

解决方案


if (str[i] == '-') {
     i += 3;
     break;
}

遇到'-'符号时停止。去掉i加一1,去掉字母e加一个空格加一2


推荐阅读