c语言从字符串中以逗号,在C ++中解析以逗号分隔的std :: string

在此程序中,我们将看到如何在C ++中解析逗号分隔的字符串。我们将在出现一些文本的地方放置一个字符串,并用逗号分隔。执行此程序后,它将把这些字符串拆分为向量类型的对象。

为了分割它们,我们使用getline()函数。该函数的基本语法如下:getline (input_stream, string, delim)

此函数用于从输入流中读取字符串或行。Input: Some strings "ABC,XYZ,Hello,World,25,C++"

Output: Separated string ABC XYZ Hello World 25 C++

算法Step 1: Create stream from given string

Step 2: While the stream is not completed

Step 2.1: Take item before comma

Step 2.2: Add item into a vector

Step 3: Return the vector

范例程式码#include

#include

#include

using namespace std;

main() {

string my_str = "ABC,XYZ,Hello,World,25,C++";

vector result;

stringstream s_stream(my_str); //create string stream from the string

while(s_stream.good()) {

string substr;

getline(s_stream, substr, ','); //get first string delimited by comma

result.push_back(substr);

}

for(int i = 0; i

cout <

}

}

输出结果ABC

XYZ

Hello

World

25

C++

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值