solution
如果有足够的空间,可以开辟另外一个char数组,当遇到空格时,将空格替换为"%20"然后存入数组。
char str[1000];
如果没有多余的空间,假设原str数组足够大,可以遍历str数组,求出空格的个数spaceCount,根据空格的个数算出需要增加的空间数:spaceCount*2。然后从后边遍历原数组,遇到空格时进行替换,并放入原数组的后边。
The algorithm is as follows:1. Count the number of spaces during the first scan of the string.2. Parse the string again from the end and for each character:»» If a space is encountered, store “%20”.»» Else, store the character as it is in the newly shifted location.
假设数组在后边有足够的空间
// Assume parsed string has sufficient free space at the endReplaceFun(char * str, int length) {
int SpaceCount = 0, NewLength, i=0;
//计算空格数目
for (i = 0; i < length; i++) {
if (str[i] == ’ ‘) {
SpaceCount++;
}
}
//重新计算需要的空间数目
NewLength = length + SpaceCount * 2;
Str[NewLength] = ‘\0’;
//从后面开始写入新数据
for (i = length — 1; i >= 0; i--) {
if (str[i] == ‘ ‘) {
str[NewLength -1 ] = ‘0‘;
str[NewLength -2 ] = ‘2’;
str[NewLength -3 ] = ‘%’;
NewLength = NewLength -3;
} else {
str[NewLength - 1] = str[i];
NewLength = NewLength -1;
}
}
}
本文详细介绍了在有限空间条件下,如何通过算法实现字符串中空格的高效替换为URL编码形式,即'%20'。具体步骤包括计算空格数量、预估所需额外空间、从后向前遍历并替换空格等。此技术适用于处理需要URL编码的文本数据。
716

被折叠的 条评论
为什么被折叠?



