博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[剑指offer] 替换空格
阅读量:4184 次
发布时间:2019-05-26

本文共 961 字,大约阅读时间需要 3 分钟。

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

代码实现如下:

class Solution {
public: void replaceSpace(char *str,int length) { if(str==NULL||length<=0) return; int old_length=0;//字符串实际长度 int Blank_Number=0;//有多少个空格 int i=0; while(str[i]!='\0') { ++old_length; if(str[i]==' ') ++Blank_Number; ++i; } //空格转换为%20之后新的字符串长度 int new_length=old_length+2*Blank_Number; if(new_length>length) return; int indexO=old_length; int indexN=new_length; while(indexO>=0 && indexN>indexO ) { if(str[indexO]==' ') { str[indexN--]='0'; str[indexN--]='2'; str[indexN--]='%'; } else { str[indexN--]=str[indexO]; } --indexO; } }};

转载地址:http://cxuoi.baihongyu.com/

你可能感兴趣的文章
hihocoder 2.29
查看>>
win7 64位系统怎么使用debug
查看>>
字典树的c++实现
查看>>
hihocoder字典树
查看>>
Leetcode Group Anagrams两种解法
查看>>
Leetcode Best Time to Buy and Sell Stock
查看>>
Leetcode Best Time to Buy and Sell Stock 2
查看>>
Best Time to Buy and Sell Stock III
查看>>
自制编译器:词法单元解析
查看>>
LeetCode 21 Merge Two Sorted Lists
查看>>
LeetCode Palindrom Number
查看>>
LeeCode 88. Merge Sorted Array两种解法
查看>>
《UNIX环境高级编程》---2 UNIX标准及实现
查看>>
LeetCode24 Swap Nodes in Pairs 25. Reverse Nodes in k-Group详解
查看>>
《UNIX环境高级编程》---3.文件I/O
查看>>
LeetCode 234. Palindrome Linked List判断链表是否回文
查看>>
LeetCode Reverse Linked List I, II详解
查看>>
《UNIX环境高级编程》---4文件和目录
查看>>
LeetCode 147. Insertion Sort List插入排序链表的高效简单解法
查看>>
LeetCode Rotate List简单易懂解法
查看>>