牛客网--替换空格
来源:互联网 发布:知乎怎么发表问题 编辑:程序博客网 时间:2024/06/02 02:14
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
基本思路: 新建一条数组,作为储存替换之后的字符串。然后在把新的数组复制到原来的数组,达到替换的目的。(前提是元素的空间足够容纳替换后的数组,如果不能,将会出错)
class Solution {public:void replaceSpace(char *str,int length) {int i = 0, count = 0, size = 0; char *new_str = NULL; if (str[i] == '\0' || str == nullptr) //判断字符串是否为空或者指针是否为空 return; while (str[i] != '\0'){ ++size; //统计字符的个数 if (isspace(str[i])) ++count; //统计空格的个数 ++i; } new_str = new char[size+count*3+1]; i = 0; int j = 0; while (str[i] != '\0'){ if (isspace(str[i])){ //替换空格 new_str[j++] = '%'; new_str[j++] = '2'; new_str[j++] = '0'; ++i; //跳过当前的空格 continue; //这条语句的作用是处理多个连续的空格 } new_str[j++] = str[i++]; //复制字符到新数组当中 } i = j = 0; while (str[i++] = new_str[j++]); //将替换之后的字符串覆盖点原来的字符串}};第二种方法:在原来的数组上替换。
基本思路: 先统计空格的个数,然后在计算空格后面的的每个字符需要向右移动几个位置。然后遇到空格时,依次用%20替换掉空格。因为%20要比原来的多出两个字符,所以每个空格后面的字符需要向右移动2 * space_count(空格个数,因为空格占去一个位置,所以乘以2)个位置。然后每替换掉一个空格就把空格计数器减1,直到为0,这时所有的空格都被替换掉了。
class Solution {public:void replaceSpace(char *str,int length) { int count = 0, i; for (i = 0; i < length; i++) //统计空格的个数 if (str[i] == ' ') ++count; i = length - 1; //定位到最后一个字符 while (i >= 0) { if (str[i] == ' ') { str[i + 2 * count] = '0'; str[i + 2 * count - 1] = '2'; str[i + 2 * count - 2] = '%'; --count; //递减空格的计数器因为count为0的时候,空格已经替换完了, } //所以这条语句不会再执行,count不会递减到小于零 else str[i + 2 * count] = str[i]; //当count递减为0时,替换的字符还是在原来的位置 --i; } }};
第三种方法,把字符串复制到一个string对象里,然后用成员函数replace替换
class Solution {public:void replaceSpace(char *str, int length){ string new_str; int i = 0; while (str[i] != '\0') { new_str.push_back(str[i]); ++i; } new_str.push_back('\0'); i = 0; //记住要把下标重置 while (new_str[i] != '\0') { if (new_str[i] == ' ') new_str.replace(i, 1, "%20");//定位到空格所在的下标,然后删除这个空格,插入“%20” ++i; } i = 0; //下标重置 for (auto ch : new_str) { str[i++] = ch; } }};
阅读全文
0 0
- 牛客网 | 替换空格
- 牛客网 替换空格
- 牛客网--替换空格
- 牛客网-剑指offer-替换空格
- 空格替换
- 替换空格
- 空格替换
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 空格替换
- 替换空格
- 替换空格
- HTML 标题 段落 图像 链接
- easyui-calendar 宽度设置
- 保存网页文章的一种方式
- 生成学习算法(Generative Learning algorithms)
- 数据结构2————队的概念和运算
- 牛客网--替换空格
- python入门5函数式编程
- 跳表(Skiplist)
- 【Python】NumPy库基本使用
- Java学习笔记 07 Iterator和Enumeration的联系和区别
- python中的变量
- Codeforces 766D Mahmoud and a Dictionary(并查集+map)
- h5增强的页面元素
- 第三讲:进程线程模型