【Cracking the coding interview】Q1.5(替换字符串)
2013-12-23 20:18
399 查看
Write a method to replace all spaces in a string with ‘%20’.
写一个函数,把字符串中所有的空格替换为%20 。
下面提供两种方法,一种分配了新的空间,一种在利用了原来的空间。
写一个函数,把字符串中所有的空格替换为%20 。
下面提供两种方法,一种分配了新的空间,一种在利用了原来的空间。
#include <iostream> #include <cstring> using namespace std; string replace(string s,char ors,string re){ if(s=="") return s; int len=s.length(); int orlen=1; int relen=re.length(); int count=0; for(int i=0;i<len;i++) if(s[i]==ors) count++; int afterlen=len+(relen-orlen)*count; char *after=new char[afterlen]; int p=0; for(int i=0;i<len;i++){ if(s[i]==ors){ i++; int j=0; while(j<relen) after[p++]=re[j++]; } after[p++]=s[i]; } after[p]='\0'; return after; } char* replace2(char *s,char ors,string re){ if(s=="") return s; int len=strlen(s); int orlen=1; int relen=re.length(); int count=0; for(int i=0;i<len;i++) if(s[i]==ors) count++; int afterlen=len+(relen-orlen)*count; //没有分配新的空间 s[afterlen]='\0'; int p=afterlen-1; for(int i=len-1;i>=0;i--){ if(s[i]==ors){ i--; int j=relen-1; while(j>=0) s[p--]=re[j--]; } s[p--]=s[i]; } return s; } int main(){ string s="I am a girl."; char s2[]="I am a girl."; cout<<"after replace"<<endl<<replace(s,' ',"%20")<<endl; cout<<"after replace"<<endl<<replace2(s2,' ',"%20"); system("pause"); return 0; }
相关文章推荐
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目2
- 【Cracking the coding interview】Q1.2(反转字符串)
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目3
- Cracking the coding interview--Q1.5
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目4
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目5
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目6
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目7
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目8
- Cracking the coding interview--Q1.5
- Cracking the coding interview--Q1.5
- Cracking the coding interview--Q1.5
- 【Cracking the coding interview】Q1.8(旋转字符串)
- Cracking the coding interview--Q1.5
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目1
- Cracking the coding interview--Q8.8
- 《Cracking the Coding Interview》——第18章:难题——题目5
- 《Cracking the Coding Interview》——第3章:栈和队列——题目1
- 《Cracking the Coding Interview》——第3章:栈和队列——题目6
- 《Cracking the Coding Interview》——第5章:位操作——题目5