Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ string split

作者:夜雨行空   发布日期:2025-06-12   浏览:81

#include <iostream>
#include <sstream>
#include <vector>

// Function to split a string by a delimiter and return a vector of substrings
std::vector<std::string> split(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(str);

    // Extract words from the stream one by one using the delimiter
    while (std::getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }

    return tokens;
}

int main() {
    std::string text = "Hello,world,this,is,a,test";
    char delimiter = ',';

    // Call the split function and store the result in a vector
    std::vector<std::string> words = split(text, delimiter);

    // Print each word in the vector
    for (const auto& word : words) {
        std::cout << word << std::endl;
    }

    return 0;
}

解释说明:

  1. split 函数:这个函数接受一个字符串 str 和一个分隔符 delimiter,然后使用 std::istringstream 将字符串按分隔符分割成多个子字符串,并将这些子字符串存储在一个 std::vector<std::string> 中返回。
  2. main 函数:在 main 函数中,定义了一个包含逗号分隔的字符串 text 和分隔符 delimiter。调用 split 函数后,结果存储在 words 向量中,最后通过循环输出每个子字符串。

这段代码展示了如何在 C++ 中实现简单的字符串分割功能。

上一篇:智能指针c++11

下一篇:c++浮点数

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站