标签:
题目描述:
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
Solution:
#include <iostream> using namespace std; void replaceBlank(char str[],int length) { if(str==NULL||length<0) return ; int originalLength=0; int numberOfBlank=0; int i=0; while(str[i]!=‘\0‘) { originalLength++; if(str[i]==‘ ‘) ++numberOfBlank; ++i; } int newLength=originalLength+numberOfBlank*2; if(newLength>length) return; int indexOfOrignal=originalLength; int indexOfNew = newLength; while(indexOfOrignal>=0&&indexOfNew>indexOfOrignal) { if(str[indexOfOrignal]==‘ ‘) { str[indexOfNew--]=‘0‘; str[indexOfNew--]=‘2‘; str[indexOfNew--]=‘%‘; } else{ str[indexOfNew--]=str[indexOfOrignal]; } --indexOfOrignal; } } int main() { char str[30]="we are happy!"; replaceBlank(str,30); cout<<str<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/xiaoying1245970347/p/5140393.html