【算法竞赛】超简单的字符串分词 | 算法竞赛技巧

本文介绍了C++中简易的字符串分词方法,包括利用cin特性、字符串流和stringstream进行分词。示例代码展示了如何处理以空格分隔的字符串,并演示了从字符串中提取整数数据。此外,还提供了一个C++实现的split函数,用于按特定字符分隔字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简易字符串分词

1.利用cin特性(不读取空格)

思路:

通过while循环 cin 输入的方式,输入单词伪装拆分字符串,通过getchar判断是否输入回车,碰到回车跳出循环

代码:

#include<bits/stdc++.h>
using namespace std;
string str;
int main() {
	while (cin >> str) {
        if(getchar(str) == '\n') break;
		cout << str << endl;
	}
}

缺点 :只能以空格分隔

2.利用字符串流拆分(默认)

原理和方法1类似

头文件:<sstream>
istringstream类	用于执行C++风格的串流的输入操作。
ostringstream类	用于执行C++风格的串流的输出操作。
stringstream类	同时支持C++风格的串流的输入输出操作。

代码:

#include<bits/stdc++.h>
using namespace std;
string s1, str;
int main() {
   getline(cin, str);
   stringstream rule(str); // 将str读入流中,这里用的构造
   while(rule >> s1){      // 将流中内容,写入s1
      cout << s1 << endl;
   }
}

缺点:只能以空格分隔

3.stringstream提取int数据

代码:

#include<bits/stdc++.h>
using namespace std;
string nums;
int num;
int main() {
   nums = "12 69 37    55a48";
   stringstream rule(nums);
   while(rule >> num){
      cout << num << endl;
   }
}

特点:遇到不符合类型就中断,无视空格读入, 写出去的就没有了。

4.c++ 实现 split

vector<string> split(string str, char del) {
	stringstream ss(str);
	string temp;
	vector<string> ret;
	while (getline(ss, temp, del)) {
		ret.push_back(temp);
	}
	return ret;
}
int main()
{
	string str_cin("one#two#three");
	vector<string> res= split(str_cin, '#');
	for (auto c : res)
		cout << c << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MuShan-bit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值