剑指Offer-替换空格

<剑指Offer>
1.请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

class Solution {
public:
void replaceSpace(char str,int length) {
int count1 =0,count2 = 0;
for(int i =0;str[i] != ‘\0’;i++)
{
count1++;
if(str[i] == ’ ')
count2++;
}
if(length < count1 + 2
count2)
return ;
for(int j = count1;j>= 0 ;j–)
{
if(str[j] != ’ ')
{
str[j+2count2] = str[j];
}
else
{
str[j+2
count2] = ‘0’;
str[j+2count2-1] = ‘2’;
str[j+2
count2-2] = ‘%’;
count2–;
}
}
}
};

你可能感兴趣的:(剑指Offer-替换空格)