空格替换

来源:互联网 发布:linux 挂载iso 编辑:程序博客网 时间:2024/05/23 16:51

原理

先oldstr指针遍历一边,记录oldlength与空格个数,然后根据newlength=oldlenth+2*space算出新字符串长度,如果出现新字符串的有效个数大于等于数组大小就返回。然后如果满足小于的话,数组可以处理,那么就从后往前依次遍历处理空格就行。要注意的点一个是传参的时候,谨防传一个NULL指针和传一个空串。空指针一访问就崩溃了,空串的话在我写的函数内不能处理,oldstr一减减,指针指向数组0号元素的前一个元素,数组就越界了。

代码

void replaceSpace(char *str, int length) {    assert(str != NULL&&*str!=0); // 预防如果传一个空串和空指针。如果传一个空串后面oldstr--,再*oldstr就崩溃了    size_t space = 0;    char * oldstr = str;    size_t oldlength = 0;    while (*oldstr != 0)    {        if (*oldstr == ' ')        {            ++space;        }        oldstr++;        oldlength++;    }    size_t newlength = oldlength + 2 * space;    if (newlength >= length) {        cout << "替换后的数组大小不够无法处理" << endl;        exit(3);    }    char * newstr = newlength + str;    *newstr = 0;    newstr--;    oldstr--; //第一个遍历完后oldstr指向原字符的\0位置,所以得先前先走一位    while (oldstr != str)    {        if (*oldstr == ' ')        {            *newstr-- = '$';            *newstr-- = '$';            *newstr-- = '$';            oldstr--;        }        else{            *newstr = *oldstr;            newstr--;            oldstr--;        }    }    if (*oldstr == ' ') //防止第一个字符为空格    {        *newstr-- = '$';        *newstr-- = '$';        *newstr = '$';    }    else{        *newstr = *oldstr;    }}