2012-09-16 61 views
0

可能重複:
Splitting a string in C++拆分函數C++

我需要拆分的功能。

有這樣的工作:

buffer = split(str, ' '); 

我searchead分割功能,tryed升壓庫,和所有的工作壞:/

+3

現在這是一個遺憾的事情。我們能幫到你什麼? – 2012-09-16 10:28:49

+1

http://stackoverflow.com/questions/236129/splitting-a-string-in-c – nhahtdh

+2

定義「工程不好」請 – TeaOverflow

回答

1

的strtok()從標準C庫是非常好,做什麼你正在尋找。除非你熱衷於從多個線程中使用它,並擔心功能不受影響,我不認爲是這種情況。

P.S.上面假設你有一個字符數組作爲輸入。如果它是一個C++字符串,仍然可以使用string.c_str在使用strtok之前獲取c字符串

1

boost lib應該也可以。

使用它,像這樣:

vector <string> buffer; 
boost::split(buffer, str_to_split, boost::is_any_of(" ")); 

新增
確保包括算法:

#include <boost/algorithm/string.hpp> 

它打印到性病::法院,像這樣:

​​
-1

我猜strtok()是你在找什麼。

它可以讓你隨時返回由給定的字符(S)分隔的第一子串:

char *string = "Hello World!"; 
char *part = strtok(string, " "); // passing a string starts a new iteration 
while (part) { 
    // do something with part 
    part = strtok(NULL, " "); // passing NULL continues with the last string 
} 

需要注意的是這個版本不能在多個線程同時使用(也有一個版本(strtok_s()more details here)它有一個額外的參數,以使其在並行環境中工作)。對於想要在循環中拆分子字符串的情況也是如此。