C用空格和引号标记一个字符串

新手上路,请多包涵

我想用 C++ 编写一些标记字符串的东西。为了清楚起见,请考虑以下字符串:

 add string "this is a string with spaces!"

这必须按如下方式拆分:

 add
string
this is a string with spaces!

是否有快速且基于标准库的方法?

原文由 the_candyman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 595
2 个回答

不需要图书馆。迭代可以完成任务(如果它像您描述的那样简单)。

 string str = "add string \"this is a string with space!\"";

for( size_t i=0; i<str.length(); i++){

    char c = str[i];
    if( c == ' ' ){
        cout << endl;
    }else if(c == '\"' ){
        i++;
        while( str[i] != '\"' ){ cout << str[i]; i++; }
    }else{
        cout << c;
    }
}

输出

add
string
this is a string with space!

原文由 Leo Zhuang 发布,翻译遵循 CC BY-SA 3.0 许可协议

我想标准库没有直接的方法。间接遵循算法将起作用:

a) 使用 string::find('\"') 搜索 ‘\”‘。如果找到任何东西,使用 string::find('\'',prevIndex) 搜索下一个 ‘\”‘,如果找到使用 string::substr() 。从原始字符串中丢弃该部分。

b) 现在以相同的方式搜索 ' ' 字符。

注意:您必须遍历整个字符串。

原文由 deeiip 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题