题目描述:
请实现一个函数,将一个字符串中的空格替换成“%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; }
时间: 2024-10-11 07:05:19