清除字符串string中的空格

1、只清除字符串首尾的空格

方法一:调用string的成员函数来进行操作

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
	//str字符串首尾各有两个空格。
	string str = "  hello this is just a test.  ";
	int len1 = str.length();

	auto s1 = str.find_first_not_of(' ');
	string res = str.substr(s1);
	auto s2 = res.find_last_not_of(' ');
	// erase默认会从所给位置开始一直删除到字符串的末尾
	res.erase(s2+1);
	int len2 = res.length();

	cout << "len1= " << len1 << " \nlen2= " << len2 << " \nres= " << res << endl;
	
	system("pause");
	return 0;
}

在这里插入图片描述
方法二

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
	//str字符串首尾各有两个空格。
	string str = "  hello this is just a test.  ";
	int len1 = str.length();

	int i = 0;
	for (; i < len1; ++i)
	{
		if (str[i] != ' ')
			break;
	}
	str.erase(0, i);

	i = str.length() - 1;
	for (; i >= 0; --i)
	{
		if (str[i] != ' ')
			break;
	}
	str.erase(i + 1);
	int len2 = str.length();

	cout << "len1= " << len1 << " \nlen2= " << len2 << " \nstr= " << str << endl;
	
	system("pause");
	return 0;
}

在这里插入图片描述


2、清除字符串中所有的空格

方法一

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main()
{
	//str字符串首尾各有两个空格。
	string str = "  hello this is just a test.  ";
	string tmp;
	vector<string> res;
	bool flag = false;

	for (int i = 0; i < str.length(); ++i)
	{
		if (str[i] != ' ')
		{
			tmp += str[i];
			flag = true;
		}
		else
		{
			if (flag)
			{
				res.push_back(tmp);
				tmp.clear();
				flag = false;
			}
		
		}
	}
	for (auto &s : res)
		cout << s << endl;
	
	system("pause");
	return 0;
}

在这里插入图片描述
方法二:使用sstream

#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;

int main()
{
	//str字符串首尾各有两个空格。
	string str = "  hello this is just a test.  ";
	string tmp;
	vector<string> res;
	
	istringstream iss(str);
	while (iss >> tmp)
	{
		res.push_back(tmp);
	}

	for (auto &s : res)
		cout << s << endl;
	
	system("pause");
	return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值