Q1.4 Write a method to replace all spaces in a string with ‘%20’.
来源:互联网 发布:c语言中的完全数 编辑:程序博客网 时间:2024/05/20 16:32
思路:
1、遍历, 原来的字符串长度len, 记录空格个数cnt, 则最后的字符串长度len+2*cnt。
2、从后往前遍历,遇到空格将其替换为"%20",否则原样拷贝
#include <iostream>#include <cstring>using namespace std;void replace(char *c){ if(c == NULL) return; int len = strlen(c); if(len == 0) return; int cnt = 0; for(int i=0; i<len; ++i) { if(c[i] == ' ') ++cnt; } int p = len + 2*cnt; c[p--] = '\0';//the space must be allocated first. for(int i=len-1; i>=0; --i) { if(c[i] == ' ') { c[p--] = '0'; c[p--] = '2'; c[p--] = '%'; } else { c[p--] = c[i]; } }}int main(){ const int len = 100; char c[len] = "abc def g h "; replace(c); cout<<c<<endl; return 0;}
0 0
- Q1.4 Write a method to replace all spaces in a string with ‘%20’.
- Write a method to replace all spaces in a string with ‘%20’.
- Write a method to replace all spaces in a string with ‘%20’
- Ch1-5: Write a method to replace all spaces in a string with ‘%20’.
- 【5】Replace all spaces in a string with ‘%20’
- Write a method to compute all permutations of a string
- Replace all spaces in string with ' ' (Cracking the Code Interview)
- Q9.5 Write a method to compute all permutations of a string
- How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
- Write a method that counts the number of occurrences of a given character in a string
- Write a method that returns all subsets of a set.
- Write a method that returns all subsets of a set
- Ch8.6: write a method to paint-fill a closed ring with the same color
- Write a C program to print all permutations of a given string
- Write a program to print all permutations of a given string
- Find All Anagrams in a String Add to List
- Q9.4 Write a method that returns all subsets of a set.
- define a static method to convert datatime to a formatted string with uesr-defined
- [Leetcode]Climbing Stairs
- C#中的二分查找
- JZ2440开发板学习------中级(二十七)
- 【环境搭建】Eclipse EE 配置 struts2
- VC 6.0 PostMeessage错误
- Q1.4 Write a method to replace all spaces in a string with ‘%20’.
- [1]C++智能指针详解
- 排序算法之插入排序
- Opencv2.4.9源码分析——MSER
- c# split函数使用
- javascript网页富文本编辑器:kindedit富文本编辑器插件的使用
- MapServer6.4.1教程学习--显示图层内类别(1-3)
- markdown常用语法总结
- openwrt代码框架