将“talk is cheap show me the code”中的空格替换为“&&&”

14 篇文章 0 订阅
7 篇文章 0 订阅

将“talk is cheap show me the code”中的空格替换为“&&&”
思路:
(1)先将字符串中空格的个数计算出来
(2)重新计算数组中的大小
(3)遇到空格,则替换,不是空格,则直接搬移即可
(4)直到原字符串中的所有元素都被替换完全
这里写图片描述

具体代码如下所示

#include<iostream>
using namespace std;
#include<assert.h>
#include<string.h>
//将“talk is cheap show me the code”中的空格替换为“&&&”
    void ReplacePace(char*array, size_t size)
    {
        int count = 0;//统计字符串中空格出现的次数
        int length = 0;//新的长度
        if (size == 0)
            return;
        else
        {
            // 先统计空格的个数
            for (int i = 0; i < size; ++i)
            {
                if (array[i] == ' ')
                    count++;
            }

            //开辟相应大小的内存
            length = size + count * 2;
            int right = length;

            //替换
            while (size < right)
            {
                if (array[size] == ' ')
                {
                    array[right--] = '&';
                    array[right--] = '&';
                    array[right--] = '&';
                    size--;
                }
                else
                {
                    array[right--] = array[size];
                    size--;
                }
            }
        }
    }

全部代码以及测试代码如下所示

#include<iostream>
using namespace std;
#include<assert.h>
#include<string.h>
//将“talk is cheap show me the code”中的空格替换为“&&&”
    void ReplacePace(char*array, size_t size)
    {
        int count = 0;//统计字符串中空格出现的次数
        int length = 0;//新的长度
        if (size == 0)
            return;
        else
        {
            // 先统计空格的个数
            for (int i = 0; i < size; ++i)
            {
                if (array[i] == ' ')
                    count++;
            }

            //开辟相应大小的内存
            length = size + count * 2;
            int right = length;

            //替换
            while (size < right)
            {
                if (array[size] == ' ')
                {
                    array[right--] = '&';
                    array[right--] = '&';
                    array[right--] = '&';
                    size--;
                }
                else
                {
                    array[right--] = array[size];
                    size--;
                }
            }
        }
    }

int main()
{
    //有效字符串
    char array[50] = "I love The World";
    cout << "替换前:" << array << endl;
    ReplacePace(array, sizeof(array) / sizeof(*array));
    cout << "替换后:" << array << endl;
    //字符串中的size为0
    char arr[10];
    ReplacePace(arr, 0);
    system("pause");
    return 0;
}

结果如下所示:
这里写图片描述

只有不停的奔跑,才能不停留在原地!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值