CareerCup1.4
2013-02-23 15:29
330 查看
Question1.4:
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in
Java, please use a character array so you can perform this operation in place.) EXAMPLE Input : "Mr John Smith " Output: "Mr%20John%20Smith"
先算出替换空格后string的结束位置,再从此结束位置开始由后向前的进行再填充,中途遇到空格则依次填充'0''2''%'
代码:
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in
Java, please use a character array so you can perform this operation in place.) EXAMPLE Input : "Mr John Smith " Output: "Mr%20John%20Smith"
先算出替换空格后string的结束位置,再从此结束位置开始由后向前的进行再填充,中途遇到空格则依次填充'0''2''%'
代码:
#include "stdafx.h" #include <string> #include <iostream> void ReplaceSpace(std::string&); int main() { using namespace std; string str; getline(cin,str); //Find the number of ' ' and the end of meaningful chars ReplaceSpace(str); cout<<str<<endl; return 0; } void ReplaceSpace(std::string& str) { int numofSpace=0; int endofchars=-1; bool meaningfulchar=false; for(int i=str.size()-1;i>=0;i--) { if(meaningfulchar&&str[i]==' ') { numofSpace++; } if(meaningfulchar==false&&str[i]!=' ') { endofchars = i; meaningfulchar = true; } } int currentPos=endofchars+2*numofSpace; for(int i=endofchars;i>=0;i--) { if(str[i]!=' ') { str[currentPos] = str[i]; currentPos--; } else { str[currentPos]='0'; str[currentPos-1]='2'; str[currentPos-2]='%'; currentPos-=3; } } }
相关文章推荐
- Tree_Graph 有序数组转BST @CareerCup
- CareerCup Implement a stack that pops out the most frequently added item
- CareerCup How would you implement a secondary sorting
- Careercup - Microsoft面试题 - 5649647234187264
- careercup-树与图 4.7
- Careercup面试题
- Career-Cup-150 1.2
- CareerCup1.5
- CareerCup-1.6
- Recursion 图像软件中的“填充”函数 @CareerCup
- Moderate 整数打印读法 @CareerCup
- Hard 不用+号实现两个数之和 @CareerCup
- CareerCup Sort an array in a special way
- CareerCup Find a subarray
- LinkLists 链表中返回倒数第n个元素 @CareerCup
- Stack_Queue 汉诺塔Hanoi问题 @CareerCup
- Tree_Graph Validate Binary Search Tree 检测一个BST是否有效 @CareerCup
- CareerCup Find the diameter of the tree
- CareerCup Write a function that given a position returns the digit in that 0123456789101112131415..
- CareerCup Round-robin tournament