c++ 字符串替换

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

we are happy.
we%20are%20happy.

// 复杂度O(n),从后向前的移动
// str4.cpp : 定义控制台应用程序的入口点。
//

#include "stdio.h"
#include "stdlib.h"
#include "iostream"

using namespace std;

void replace(char str[]);


int main(int argc, char * argv[])
{
	char p[100] = "we are happy.";
	replace(p);
	cout<<p<<endl;
	system("pause");
	return 0;
}

void replace(char str[])
{
	if(str == NULL) return;
	char * ps = str;
	char * pn;
	int num = 0;
	 
	while(*ps != '\0')
	{
		if(*ps == ' ')
			num++;
		ps++;
	}

	// ps 指向原字符串的末尾
	// pn 指向新的字符串的末尾
	pn = ps + 2 * num;

	while(ps >= str && pn > ps)
	{
		while(*ps != ' ' && ps >= str && pn > ps)
		{
			*pn-- = *ps--;
		}
		
		if(ps >= str && pn > ps)
		{
			*pn-- = '0';
			*pn-- = '2';
			*pn-- = '%';
			ps--;
		}
	}

}




// str3.cpp : 定义控制台应用程序的入口点。
//

#include "stdio.h"
#include "stdlib.h"
#include "iostream"

using namespace std;

char * convert(char * p);

int main(int argc, char * argv[])
{
	char p[] = "weisong";
	char * r = convert(p);
	if(r)
	{
		cout<<r<<endl;
	}

	char p2[] = "we are happy.";
	cout<<p2<<endl;
	r = convert(p2);
	if(r)
	{
		cout<<r<<endl;
	}

	system("pause");
	return 0;
}

char * convert(char p[])
{
	if(p == NULL)
		return NULL;
	if(strstr(p, " ") == NULL)
		return p;

	int length = strlen(p);
	int blankNum = 0;
	char * s = p;
	while(*p != '\0')
	{
		if(*p == ' ')
			blankNum++;
		p++;
	}

	int newLength = length + blankNum * 2;
	char * result  = new char[newLength * sizeof(char) + 1];//(char*)malloc(newLength * sizeof(char) + 1);
	if(result == NULL) return NULL;

	p = s;
	char * t = result;

	char * pre = p;
	while(*p != '\0')
	{
		bool f = false;
		// 找到空格
		while(*p != ' ')
		{
			if(*p == '\0')
			{
				f = true;
				break;
			}

			pre = p;
			*t++ = *p;
			p++; 
		}

		if(f)
			break;

		// 处理空格
		*t++ = '%';
		*t++ = '2';
		*t++ = '0';
		p++;
	}

	*t++ = '\0';

	return result;
}



你可能感兴趣的:(c++ 字符串替换)