這樣的:
#include <stdio.h>
char *reduce_and_trim(char *s);
int main(void) {
FILE *input_file = stdin;
char line[50];
while (fgets(line,50, input_file) != NULL) {
printf("'%s'\n", reduce_and_trim(line));
}
fclose(input_file);
}
#include <string.h>
char *reduce_and_trim(char *s){
static const char *whitespaces = " \t\n";//\t:tab, \n:newline, omit \f\r\v
size_t src = strspn(s, whitespaces);//Trim of the beginning
size_t des = 0;//destination
size_t spc = 0;//number of whitespaces
while(s[src] != '\0'){
if((spc = strspn(s+src, whitespaces)) != 0){
src += spc;
s[des++] = ' ';//reduce spaces
} else {
s[des++] = s[src++];
}
}
if(des && s[des-1] == ' ')
s[des-1] = 0;//Trim of end
else
s[des] = 0;
return s;
}
你試過了什麼?您發佈的小代碼有語法錯誤。 –
我編輯它。現在可以了? – StackUser
通常,我試圖使用'strtok',但我沒有成功達到這個問題的最終解決方案。 – StackUser