2012-04-07 62 views
13

我在寻找一种简单的方式来标记串输入而不使用非默认库诸如升压,等等C++标记化字符串

例如,如果用户输入forty_five,我想单独四十五个使用_作为分隔符。

+1

的可能重复[如何记号化一字符串在C++?](http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c) – Corbin 2012-04-07 04:20:58

+0

http://stackoverflow.com/a/236803/240633 – ergosys 2012-04-07 04:27:31

回答

26

将一个字符串转换为标记的矢量(线程安全):

std::vector<std::string> inline StringSplit(const std::string &source, const char *delimiter = " ", bool keepEmpty = false) 
{ 
    std::vector<std::string> results; 

    size_t prev = 0; 
    size_t next = 0; 

    while ((next = source.find_first_of(delimiter, prev)) != std::string::npos) 
    { 
     if (keepEmpty || (next - prev != 0)) 
     { 
      results.push_back(source.substr(prev, next - prev)); 
     } 
     prev = next + 1; 
    } 

    if (prev < source.size()) 
    { 
     results.push_back(source.substr(prev)); 
    } 

    return results; 
} 
+0

+ 1比我链接到的strstream更吸引人。 – ergosys 2012-04-08 03:52:04

+0

@ergosys谢谢。 – 2012-05-24 00:28:14

+0

+1为优雅 – eeerahul 2013-01-06 12:18:45

1

您可以使用strtok_r函数,但请仔细阅读手册页,以便了解它如何保持状态。

1

this教程,这是我迄今发现的符号化迄今为止最好的教程。它涵盖的包括使用函数getline()find_first_of()在C++的std不同的方法实现的)C中的最佳实践,并的strtok(