我尝试编写一个函数来获取一个字符串并创建一个新字符串但没有多个空格(单词之间只留下 1 个空格)。
到目前为止,我写了这个,但由于某种原因它崩溃了,调试器什么也没显示。
我也不知道我需要把免费功能放在哪里......
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* upgradestring(char* oldtext);
int main()
{
char str1[] = "Chocolate Can Boost Your Workout" ;
printf("%s\n", str1);
printf("\n%s\n", upgradestring(str1));
return 0;
}
char* upgradestring(char* oldtext)
{
int i,j, count = 1;
char *newstr;
for (i = 0; oldtext[i] != '\0'; i++)
{
if (oldtext[i] != ' ')
count++;
else if (oldtext[i - 1] != ' ')
count++;
}
newstr = (char*)malloc(count * sizeof(char));
if (newstr == NULL)
exit(1);
for (i = 0, j = 0; (oldtext[i] != '\0')|| j<(count+1); i++)
{
if (oldtext[i] != ' ')
{
newstr[j] = oldtext[i];
j++;
}
else if (oldtext[i - 1] != ' ')
{
newstr[j] = oldtext[i];
j++;
}
}
return newstr;
}
最佳答案
您正在寻址 [i-1]
,如果 i==0
,它不在原始数组的范围内。
这里是你如何做到的:
简单地一个一个复制,如果字符是' ',当它是' '时继续跳过,否则前进一个。
static size_t newlen(char const *o)
{
size_t r=0;
while(*o){
r++;
if(*o==' ')
while(*o==' ')
o++;
else
o++;
}
return r;
}
char *upgradestring(char const *o)
{
char *r, *p;
size_t len = newlen(o);
if( 0==(r = malloc(len+1)))
return 0;
r[len]=0;
for(p=r;*o;){
*p++=*o;
if(*o==' ')
while(*o==' ')
o++;
else
o++;
}
return r;
}
int main()
{
char str1[] = "Chocolate Can Boost Your Workout" ;
char *new;
printf("%s\n", str1);
if(0 == (new = upgradestring(str1)))
return 1;
printf("%s\n", new);
free(new);
}
分配失败最好通过返回码表示(您不希望库函数在失败时中止您的程序)。
为了能够释放返回的字符串,您首先必须将其捕获到一个变量中。
关于c - 从字符串中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44605024/