【字符串与数组】
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]=' '; return newStr; }
作者:Viidiot 微信公众号:linux-code