getline 切割字符串

getline 切割字符串
1、使用 iostream 中 getline 函数截取 string
函数原型:

std::istream &std::getline<char, std::char_traits<char>, std::allocator<char>>(std::istream &_Istr, std::string &_Str,     char _Delim)

getline(istream && is,string&str,char delim)
/* 需要使用的头文件 */

#include <iostream>
//getline 函数
#include <sstream>
//stringstream 类

using namespace std;

int main () {
	string str = "/home/name/Desktop/";
	string res;
	stringstream sstr(str);
	while (getline(sstr, res, '/')) {
		cout << res << endl;
	}
}
输出:
空字符
home
name
Desktop
C++中,可以使用stringstream和getline()函数来分割字符串。 stringstream是一个流类,可以将字符串转换为其他类型的数据。它提供了一种方便的方法来从字符串中提取数据,并将其存储到不同的变量中。 下面是使用stringstream和getline()函数来分割字符串的示例代码: ```cpp #include <iostream> #include <sstream> #include <string> #include <vector> int main() { std::string str = "Hello,World,How,Are,You"; std::vector<std::string> tokens; std::stringstream ss(str); std::string token; while (getline(ss, token, ',')) { tokens.push_back(token); } for (const auto& t : tokens) { std::cout << t << std::endl; } return 0; } ``` 在上面的代码中,我们首先定义了一个字符串str,其中包含了多个单词,这些单词之间使用逗号进行分隔。 然后,我们创建了一个stringstream对象ss,并将字符串str传递给它。接下来,我们定义了一个字符串变量token,用于存储每个分割后的单词。 在while循环中,我们使用getline()函数从stringstream对象ss中提取每个单词,并将其存储到token变量中。getline()函数的第三个参数是分隔符,这里我们使用逗号作为分隔符。 每次调用getline()函数后,我们将token变量的值添加到一个vector容器tokens中。 最后,我们使用一个for循环遍历tokens容器,并将每个单词打印到控制台上。 运行上述代码,输出将是: ``` Hello World How Are You ``` 这样,我们就成功地使用stringstream和getline()函数将字符串分割成了多个单词。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值