不懂为啥发帖的时候不允许我用代码格式提交 故在评论区再次附上代码#include<iostream>
using namespace std;
void ReplaceBlank(char str[], int length)
{
if (str == nullptr && length <= 0)
return;
/*originalLength 为字符串str的实际长度*/
int originalLength = 0;
int numberOfBlank = 0;
int i = 0;
while (str[i] != '\0')
{
++originalLength;
if (str[i] == ' ')
++numberOfBlank;
++i;
}
/*newLength 为把空格替换成'%20'之后的长度*/
int newLength = originalLength + numberOfBlank * 2;
if (newLength > length)
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
{
if (str[indexOfOriginal] == ' ')
{
str[indexOfNew--] = '0';
str[indexOfNew--] = '2';
str[indexOfNew--] = '%';
}
else
{
str[indexOfNew--] = str[indexOfOriginal];
}
--indexOfOriginal;
}
}
void replaceblank(char str[], int length)
{
cout << str << endl;
if (str == nullptr && length <= 0)
return;
int originalLength = 0;
int numOfBlank = 0;
int i = 0;
while (str[i] != '\0')
{
originalLength++;
if (str[i] == ' ')
numOfBlank++;
i++;
}
int newLength = originalLength + numOfBlank * 2;
if (newLength > length)
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0&&indexOfNew>indexOfOriginal)
{
if (str[indexOfOriginal] == ' ')
{
str[indexOfNew--] = '0';
str[indexOfNew--] = '2';
str[indexOfNew--] = '%';
}
else
{
str[indexOfNew--] = str[indexOfOriginal];
}
--indexOfOriginal;
}
cout << str << endl;
}
void main()
{
char str[] = "i o v";
replaceblank(nullptr, 0);
//ReplaceBlank(nullptr, 0);
system("pause");
}
|