替换空格

题目:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。

解题思路:以时间效率优先的话,可以分为两种处理办法,一种利用辅助内存,即新开辟一个数组,时间复杂度为O(n)

另一种不用辅助内存,即在原数组上操作:

1.先遍历一次数组,统计空白字符个数,记录在blankcount中,数组的最后一位‘’的下标记录在index中;

2.求得替换空格后的数组最后一位下标lastindex=index+2*blankcount;

3.从后往前遍历数组,替换数组中的空格。

实现代码如下:

#include<iostream>
#include<string>
using namespace std;
void replace(char *array,int length)
{
    if(array!=NULL&&length>0)//判断参数是否合法
    {
        int blankcount=0,index=0;//blankcount记录空格数,index记录数组中最后一为''的下标
        while(array[index]!='')//统计空格数
        {
            if(array[index]==' ')
                blankcount++;
            index++;
        }
        //置换空格之后实际数组最后一位的下标
        int lastindex=index+2*blankcount;
        //判断数组容量是否合格
        if(lastindex>length)
        {
            cout<<"数组长度不够!"<<endl;
            return;
        }
        //循环将空格替换为“%20”
        while(index<lastindex&&index>=0)
        {
            if(array[index]==' ')
            {
                array[lastindex--]='0';
                array[lastindex--]='2';
                array[lastindex--]='%';
                index--;
            }
            else
            {
                array[lastindex--]=array[index--];
            }
        }
    }
}
int main()
{
    char a[100]={' ','a','b',' ',' ','c','d',' ','e','f',' '};//测试用例
    cout<<a<<endl;
    replace(a,100);
    cout<<a<<endl;
    char *b="asdasd";
    cout<<b<<endl;
    replace(b,20);
    cout<<b<<endl;
    char c[20]={' ',' '};
    cout<<c<<endl;
    replace(c,20);
    cout<<c<<endl;
    char name[20];return 0;
}

结果:

原文地址:https://www.cnblogs.com/runninglzw/p/4477568.html