编写一个函数接受一个字符串作为参数,并删除字符串中的空格。
函数代码
#include <stdio.h>
char *strDelSpace(char *str)
{
char *pc_inspect = str;
char *pc_locate = str;
while (pc_inspect == pc_locate && *pc_inspect)
{
if (*pc_inspect == ' ')
{
while (*pc_inspect == ' ')
pc_inspect++;
}
else
{
pc_inspect++;
pc_locate++;
}
}
while (*pc_inspect)
{
while (*pc_inspect == ' ')
pc_inspect++;
*pc_locate = *pc_inspect;
pc_locate++;
pc_inspect++;
}
*pc_locate = '\0';
return str;
}
函数测试
#include <stdio.h>
char *strDelSpace(char *str);
int main(int argc, char const *argv[])
{
char str1[] = "this is a string";
char str2[] = "thisanotherstr ing";
char str3[] = " thisanotherstr ing";
strDelSpace(str1);
strDelSpace(str2);
strDelSpace(str3);
printf("*%s*\n", str1);
printf("*%s*\n", str2);
printf("*%s*\n", str3);
return 0;
}
char *strDelSpace(char *str)
{
char *pc_inspect = str;
char *pc_locate = str;
while (pc_inspect == pc_locate && *pc_inspect)
{
if (*pc_inspect == ' ')
{
while (*pc_inspect == ' ')
pc_inspect++;
}
else
{
pc_inspect++;
pc_locate++;
}
}
while (*pc_inspect)
{
while (*pc_inspect == ' ')
pc_inspect++;
*pc_locate = *pc_inspect;
pc_locate++;
pc_inspect++;
}
*pc_locate = '\0';
return str;
}
输出
>
*thisisastring*
*thisanotherstring*
*thisanotherstring*