将字符串中的空格替换为%20

目录

(1) 利用C++的string实现

(2)直接位移

(3) 用一个额外的数组保存结果

(4)优先计算出替换后数组的长度后倒放


题目:将字符串中的空格替换为”%20“

例如:输入:abc defgx yz

           输出:abc%20defgx%20yz

(1) 利用C++的string实现

#include <string>
#include <iostream>

using namespace std;
void Replace(string& str)
{
	size_t pos = 0;
	while ((pos = str.find(' ', pos)) != string::npos)
	{
		str.erase(pos, 1);
		str.insert(pos, "%20");
	}
}

int main()
{
	string str = "abc defgx yz"; 
	Replace(str);
	cout << str << endl;
}

解释一下代码里的npos:

npos是一个表示“不存在的位置”的常数,通常用于字符串操作中指示没有找到匹配项的情况。

在C++中,string::npos是一个特殊的值,它被定义为size_t类型的最大值,通常用来表示在字符串中进行查找操作时未找到目标子串或字符的情况。npos的具体值为-1,但由于size_t是一个无符号整数类型,这个-1实际上代表了该类型的最大可能值。

例如,在使用std::string的find方法时,如果查找的子字符串不存在于原字符串中,`find`方法会返回string::npos。因此,可以通过检查find方法的返回值是否等于string::npos来判断是否找到了目标子串。

npos不仅用于字符串操作,还可能用于其他需要表示“不存在位置”或“最大可能值”的场景。在不同的上下文中,npos可能有不同的含义,但其核心概念是一致的,即代表了一个超出常规范围的特殊值。

(2)直接位移

指针p:用于寻找空格,遇到空格后停止;

指针q:每次指向字符串的最后一个,用于将p后的数据都向后移。

#include <iostream>

using namespace std;
void Replace(char str[])
{
	int p=0;
	int q = strlen(str)-1;
	while (str[p] != '\0')
	{
		if (str[p] == ' ')
		{
			while (q!=p)
			{
				str[q + 2] = str[q];
				q--;
			}
			q = strlen(str) - 1;
			str[p] = '%';
			str[p + 1] = '2';
			str[p + 2] = '0';
			p += 2;
		}
		p++;
	}
}

int main()
{
	char str[100] = "abc def gh";
	Replace(str);
	for (int i = 0; i < strlen(str); i++)
		cout << str[i];
}

(3) 用一个额外的数组保存结果

str1[ ]为题目数组,str2[ ]用来保存结果;

指针i:指向str1,遇到空格向str2放入"%20",否则直接将str[i]放入str2;

指针j:指向str2,用于填入数据。

#include <iostream>
using namespace std;
void Replace(char str1[],char str2[])
{
	int i = 0;
	int j = 0;
	while (str1[i] != '\0')
	{
		if (str1[i] == ' ')
		{
			str2[j++] = '%';
			str2[j++] = '2';
			str2[j++] = '0';
		}
		else
		{
			str2[j++] = str1[i];
		}
		i++;
	}
}

int main()
{
	char str1[100] = "abc def gh";
	char str2[100] = "\0";
	Replace(str1,str2);
	for (int i = 0; i < strlen(str2); i++)
		cout << str2[i];
}

(4)优先计算出替换后数组的长度后倒放

指针j:指向新数组的末尾;

指针i:指向原数组的末尾。

http://t.csdnimg.cn/0hAue

#include <iostream>

using namespace std;
void Replace(char str[])
{
	int i=0;
	int Before_len = strlen(str);
	int j = Before_len -1;
	while (str[i] != '\0')
	{
		if (str[i] == ' ')
			j += 2;
		i++;
	}//经此处理后的j指向新数组的末尾
	i = Before_len - 1;//i指向原数组的末尾
	while (i >= 0 && j >= 0&&i!=j)
	{
		if (str[i] == ' ')
		{
			str[j--] = '0';
			str[j--] = '2';
			str[j--] = '%';
		}
		else
		{
			str[j--] = str[i];
		}
		i--;
	}
}

int main()
{
	char str[100] = "abc def gh";
	Replace(str);
	for (int i = 0; i < strlen(str); i++)
		cout << str[i];
}
 

参考文章:http://t.csdnimg.cn/QjycL


      喜欢的小伙伴还请点赞收藏,(❁´◡`❁)( o=^•ェ•)o ┏━┓


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值