溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

字符串分割成單詞的C++方式

發(fā)布時(shí)間:2024-10-09 14:49:16 來(lái)源:億速云 閱讀:78 作者:小樊 欄目:編程語(yǔ)言

在C++中,可以使用<sstream>庫(kù)中的stringstreamgetline()函數(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ù)中打印它們。

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

c++
AI