我試圖編寫一個函數來獲取一個字符串並創建一個新的字符串,但沒有多個空格(在單詞之間只留下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;
}
是的,我需要返回一個新字符串相同oldstring,但只有1個詞語之間的空間 – 420Friendlly
計數是新的字符串的大小與1個空間和計數+ 1是'\ 0' – 420Friendlly