《劍指offer》面試題4(替換空格)

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
void replaceBlank(char* str);
int main()
{
    char* str;
    str = new char[100];
    strcpy(str,"  str  str  ");
    replaceBlank(str);
    cout<<str<<endl;
    strcpy(str,"str");
    replaceBlank(str);
    cout<<str<<endl;
    replaceBlank(NULL);
    //cout<<str<<endl;
    strcpy(str,"");
    replaceBlank(str);
    cout<<str<<endl;
    strcpy(str," ");
    replaceBlank(str);
    cout<<str<<endl;
    strcpy(str,"  ");
    replaceBlank(str);
    cout<<str<<endl;
    return 0;
}

void replaceBlank(char* str)
{
    if(str == NULL) return;
    int length = strlen(str);
    int blankcount = 0;
    for(int i=0;i<length;i++)
        if(str[i] == ' ')
            blankcount++;
    int newlength = length + 2*blankcount;
    str[newlength] = '\0';
    int p = newlength-1;
    for(int i = length-1;i>=0;i--)
    {
        if(str[i] == ' ')
        {
            str[p--] = '0';
            str[p--] = '2';
            str[p--] = '%';
        }
        else
            str[p--] = str[i];
    }
}
/*char* replaceBlank(const char* str)     //創建新的內存空間
{
    if(str == NULL) return NULL; //strlen()函數的參數不能是NULL
    int length = strlen(str);
    char* newstr = new char[length*3+1];
    int p = 0;
    for(int i=0;i<length;i++)
    {
        if(str[i] == ' ')
        {
            newstr[p++] = '%';
            newstr[p++] = '2';
            newstr[p++] = '0';
        }
        else
            newstr[p++] = str[i];
    }
    newstr[p] = '\0';
    return newstr;
}*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章