【剑指offer】题目二

//实现一个函数:把字符串中的每个空格替换成"%20"。例如输入"We are happy."则输出"We%20are%20happy."
//思路:(本题要求在原来的字符串的基础上修改)统计出"新"字符串的总长度,设置两个指针,分别指向"新"的尾部和旧字符串的尾部...(详见附件)
// swordFingerOffer_2.cpp
//

#include "stdafx.h"
#include<iostream>
using namespace std;

void replaceBlank(char tmpString[], char replace[]) {
	//1.统计空格数,计算出新的字符串需要的空间
	//定义两个指针,用于指向字符串
	char *tmpPtr = tmpString;
	char *tmpRepStr = replace;
	int blankCount = 0;		//空格数
	while (*tmpPtr != '') {
		if (*tmpPtr == ' ')
			blankCount++;
		tmpPtr++;
	}
	//new ptr
	char *p2 = tmpPtr + blankCount * 2;

	while (tmpPtr != p2) {
		if (*tmpPtr != ' ') {
			*p2 = *tmpPtr;
			tmpPtr--;
			p2--;
		}
		else if (*tmpPtr == ' ') {
			tmpPtr--;
			while (*tmpRepStr != '') {
				*p2 = *tmpRepStr;
				p2--;
				tmpRepStr++;
			}
			//p2--;
			tmpRepStr = replace;
		}
	}	
}
int main()
{
	char tmpSrting[100] = "Hi kevin,just think about it";		//方法的缺点是要提前申请好足够长的空间
	//char tmpSrting[100] = "Hi ke";		//方法的缺点是要提前申请好足够长的空间
	char replaced[] = "02%";
	replaceBlank(tmpSrting, replaced);
	cout << tmpSrting << endl;

    return 0;
}
输出:

注:本题的思想类似于【找出带环单链表的入口】这个题目的思路。


原文地址:https://www.cnblogs.com/xuelisheng/p/9224839.html