剑指Offer02 替换空格

时间:2023-03-08 17:29:42
剑指Offer02 替换空格
 /*************************************************************************
> File Name: 02_Replace_Blank.c
> Author: Juntaran
> Mail: JuntaranMail@gmail.com
> Created Time: 2016年08月24日 星期三 01时28分33秒
************************************************************************/ #include <stdio.h> void ReplaceBlank(char* str)
{
if (str==NULL)
{
return;
} int blankCount = ;
int alphaCount = ;
int i = ;
while (str[i] != '\0')
{
if (str[i] == ' ')
blankCount ++;
alphaCount ++; i ++;
}
printf("alphaCount is %d\n", alphaCount);
printf("blankCount is %d\n", blankCount); int newLength = alphaCount + *blankCount;
printf("newLength is %d\n", newLength);
int p1 = alphaCount + ;
int p2 = newLength + ;
while (p1>= && p2>p1)
{
if (str[p1] == ' ')
{
str[p2--] = '';
str[p2--] = '';
str[p2--] = '%';
}
else
{
str[p2--] = str[p1];
}
p1 --;
}
} int main()
{
char str[] = "We are Happy!";
printf("Before: %s\n", str);
ReplaceBlank(str);
printf("After: %s\n", str);
}