《剑指offer》面试题4(替换空格)

来源:互联网 发布:网络风靡的性感骚彤彤 编辑:程序博客网 时间:2024/05/29 07:17
#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;}*/

0 0
原创粉丝点击