当前位置:编程学习 > 网站相关 >>

[google面试CTCI] 1-5.替换字符串中特定字符

【字符串与数组】
 
Q:Write a method to replace all spaces in a string with ‘%20’
 
题目:写一个算法将一个字符串中的空格替换成%20
 
解答:
 
很直观的解法,首先统计出字符串中空格个数,然后分配新的内存空间,依次从头到尾复制原字符串到新字符串中,遇到空格,则复制%20这三个字符。还有没有其他更好点的方法呢??
 
char* replace(char* str){
int len=strlen(str);
int spaceNum=0;
int i;
for(i=0;i<len;++i){
if(str[i]==' ')
++spaceNum;
}
char* newStr=malloc((len+2*spaceNum+1)*sizeof(char));
int index=0;
for(i=0;i<len;++i){
if(str[i]==' '){
newStr[index++]='%';
newStr[index++]='2';
newStr[index++]='0';
}
else
newStr[index++]=str[i];
}
newStr[index]='\0';
return newStr;
}
补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,