Created
April 25, 2019 14:54
-
-
Save necusjz/cbc6c2d8837c42c565c31280b72c9c0b to your computer and use it in GitHub Desktop.
面试题 5:替换空格
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void ReplaceBlank(char string[], int length) { | |
if(string == nullptr || length <= 0) { | |
return; | |
} | |
int originalLength = 0; | |
int numberOfBlank = 0; | |
int i = 0; | |
while(string[i] != '\0') { | |
++originalLength; | |
if(sting[i] == ' ') { | |
++numberOfBlank; | |
} | |
++i; | |
} | |
int newLength = originalLength + numberOfBlank * 2; | |
if(newLength > length) { | |
return; | |
} | |
int indexOfOriginal = originalLength; | |
int indexOfNew = newLength; | |
while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal) { | |
if(string[indexOfOriginal] == ' ') { | |
string[indexOfNew--] = '0'; | |
string[indexOfNew--] = '2'; | |
string[indexOfNew--] = '%'; | |
} | |
else { | |
string[indexOfNew--] = string[indexOfOriginal]; | |
} | |
--indexOfOriginal; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment