代码如下:
#include<stdio.h> #include<stdlib.h> void ReplaceBlank( char* str, int len) { if (str == NULL||len <= 0) { return; } int originalLen = 0; int numberOfBlank = 0; int i = 0; while (str[i]!='\0') { ++originalLen; if (str[i] == ' ') ++numberOfBlank; ++i; } int newLen = originalLen + numberOfBlank * 2; if (newLen > len) { return; } int index0fOriginal = originalLen; int indexOfNew = newLen; while (index0fOriginal >= 0 && indexOfNew>index0fOriginal) { if (str[index0fOriginal] == ' ') { str[indexOfNew--] = '0';//因为要传入‘\0’ str[indexOfNew--] = '2'; str[indexOfNew--] = '%'; } else { str[indexOfNew--] = str[index0fOriginal]; } --index0fOriginal; } } int main() { char str[30] = "we are happy"; ReplaceBlank(str, sizeof(str)/sizeof(str[1])); printf("%s",str); system("pause"); return 0; }
核心代码:
void ReplaceBlank( char* str, int len) { if (str == NULL||len <= 0) { return; } int originalLen = 0; int numberOfBlank = 0; int i = 0; while (str[i]!='\0') { ++originalLen; if (str[i] == ' ') ++numberOfBlank; ++i; } int newLen = originalLen + numberOfBlank * 2; if (newLen > len) { return; } int index0fOriginal = originalLen; int indexOfNew = newLen; while (index0fOriginal >= 0 && indexOfNew>index0fOriginal) { if (str[index0fOriginal] == ' ') { str[indexOfNew--] = '0';//因为要传入‘\0’ str[indexOfNew--] = '2'; str[indexOfNew--] = '%'; } else { str[indexOfNew--] = str[index0fOriginal]; } --index0fOriginal; } }