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

替换字符串中的空格为$$$。要求时间复杂度为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;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值