【C++】将字符串中的空格替换成字符

来源:互联网 发布:淘宝网防晒衣 编辑:程序博客网 时间:2024/04/27 21:37

替换字符串中的空格为$$$。要求时间复杂度为O(N)

例如:将”talk is cheap show me the code”替换为:

“talk$$$is$$$cheap$$$show$$$me$$$the$$$code

思路:将原数组的空格替换为特殊符号,那么原数组的大小也改变了,因此我们需要定义新的字符串大小,因为将空格替换为$$$原数组大小每个空格的地方增加两个空格大小,新数组 = 原数组大小+2*空格数。

代码实现:

void space_to_symbol(){    char str[100] = "talk is cheap show me the code";    cout << str << endl;    char* start = str;    int space_count = 0;    int old_length = 0;    while (*start)    {        if (*start == ' ')        {            space_count++;        }        old_length++;        start++;    }    int new_length = old_length + space_count * 2;    while (old_length >= 0)    {        if (str[old_length] == ' ')        {            str[new_length--] = '$';            str[new_length--] = '$';            str[new_length--] = '$';        }        else        {            str[new_length--] = str[old_length];        }        old_length--;    }    cout << str << endl;}int main(){    space_to_symbol();    system("pause");    return 0;}

这里写图片描述

阅读全文
1 0