以下是用'%20'替換字符串中的所有空格的方法。它通常工作正常,但在執行完成'運行時檢查失敗#2 - S'時抱怨。我的for循環有問題嗎?運行時檢查失敗#2 - S,Visual Studio C++
void replaceSpace(char *s) {
int spaces = 0;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == ' ') {
spaces++;
}
}
// new string that includes overwriting space, and two additional chars
int newLen = strlen(s) + spaces * 2;
s[newLen] = '\0';
for (int i = strlen(s) - 1; i >= 0; i--) {
if (s[i] == ' ') {
s[newLen - 1] = '0';
s[newLen - 2] = '2';
s[newLen - 3] = '%';
newLen -= 3;
}
else {
s[newLen - 1] = s[i];
--newLen;
}
}
}
char test[] = "rep lace Spac e";
replaceSpace(test);
cout << test << endl; //rep%20lace%20Spac%20e
編輯:我跑了這cpp shell,並沒有任何問題奇怪。我試着更新visual studio 2015,然後回報。
edit2:不,同樣的錯誤。
*貌似*工作是未定義行爲的可能性之一。 –