【发布时间】:2017-11-20 03:53:50
【问题描述】:
我尝试编写一个函数,它获取一个字符串并创建一个新字符串,但没有多个空格(单词之间只留 1 个空格)。
到目前为止,我写了这个,但由于某种原因它崩溃了,调试器什么也没显示。
我也不知道需要把free函数放在哪里...
#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;
}
【问题讨论】:
-
是的,我需要返回一个与旧字符串相同但单词之间只有 1 个空格的新字符串
-
count 是新字符串的大小,有 1 个空格,count+1 是 '\0'
标签: c string function pointers memory-management