您好,登錄后才能下訂單哦!
在C++中,可以使用<sstream>
庫(kù)中的stringstream
和getline()
函數(shù)來(lái)將字符串分割成單詞。以下是一個(gè)示例代碼:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
std::vector<std::string> split(const std::string& str, char delim) {
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delim)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string str = "Hello, World! This is a test.";
char delim = ' ';
std::vector<std::string> words = split(str, delim);
for (const auto& word : words) {
std::cout << word << std::endl;
}
return 0;
}
在這個(gè)示例中,我們定義了一個(gè)名為split
的函數(shù),它接受一個(gè)字符串和一個(gè)分隔符作為參數(shù),并返回一個(gè)包含分割后的單詞的vector
。我們使用stringstream
來(lái)讀取字符串,并使用getline()
函數(shù)來(lái)獲取以分隔符分隔的單詞。然后,我們將這些單詞添加到tokens
向量中,并在main
函數(shù)中打印它們。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。