我正在嘗試下面的代碼,但得到一個錯誤的輸出。例如,我輸入「a b c」,我希望結果是「abc」,但結果是中文字符。如何在C中刪除字符串中的空格?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
/* function prototype */
char *sweepSpace(char *sentence);
int main()
{
char str[80];
printf("Enter a string: ");//enter a string for example "a b c'
gets(str);
printf("Result: %s ", sweepSpace(str));//should print "abc"here
return 0;
}
char *sweepSpace(char *setence)
{
char b[80];
int i = 0;
while (*setence != NULL)
{
//if not reach the end
if (!isspace(*setence))
{
//if not a space
b[i] = *setence;//assign setence to b
i++;//increment
}
setence++;//pointer increment
}
b[i]= "\0";
return b;//return b to print
}
b [i] =「\ 0」 - 將其更改爲b [i] ='\ 0'; (使用單引號) –
'*句子!= NULL',這乍一看似乎不正確。 'NULL'通常用於指定內存地址。你應該使用''\ 0'' –
我在那裏看到一個'gets'!請**從不**使用'gets'。它被棄用和不安全。 – ajay