[NK]替换空格

替换空格
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

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

/*
从前往后替换,后面的字符要不断往后移动,要多次移动,所以效率低下
从后往前,先计算需要多少空间,然后从后往前移动,则每个字符只为移动一次,这样效率更高一点。
*/

void replaceSpace(char *str, int length) {
    int spacenum = 0;//spacenum为计算空格数
    for (int i = 0; i< length; i++) {
        if (str[i] == ' ')
            spacenum++;
    }
    int indexold = length -1; //indexold为替换前的str下标
    int newlength = length + spacenum * 2;//计算空格转换成%20之后的str长度
    int indexnew = newlength - 1;//indexold为为把空格替换为%20后的str下标
    //str.setLength(newlength);//使str的长度扩大到转换成%20之后的长度,防止下标越界
    for (; indexold >= 0 && indexold<newlength; --indexold) {
        if (str[indexold] == ' ') 
        {  
            str[indexnew--] =  '0';
            str[indexnew--] = '2';
            str[indexnew--] = '%';
        }
        else {
            str[indexnew--] =  str[indexold];
        }
    }
}

int main()
{
    char str[] = "Good News!";
    int length = 11;
    replaceSpace(str, length);
    cout << str << endl;
    system("PAUSE");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014630431/article/details/81051216
今日推荐