1. 程式人生 > >牛客網 空格替換 C++

牛客網 空格替換 C++

時間限制:1秒 空間限制:32768K 熱度指數:740599

本題知識點: 字串

題目描述

請實現一個函式,將一個字串中的每個空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

#include<iostream>
using namespace std;
#include<cstring>
void replaceSpace(char *str, int length);
void main(){
    char *a = "hello world";
    replaceSpace(a, 20);
    cout << a;
    system("pause");
}


void replaceSpace(char *str, int length) {
    int origin = 0;
    int blank = 0;
    for (int i = 0; i < length; i++)
    {
        if (str[i] == ' ')
        {
            blank++;
        }
        origin++;
    }

    int newlength = origin + 2 * blank;
    if (newlength > length)
    {
        return;
    }
    int index_origin = origin;
    int index_new = newlength;
    while ((index_origin >= 0 )&& (index_new > index_origin))
    {
        if (str[index_origin] == ' ')
        {
            str[index_new--] = '0';
            str[index_new--] = '2';
            str[index_new--] = '%';
        }
        else
        {
            str[index_new--] = str[index_origin];
        }
    }
}