#include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> void RemoveExtraSpace(char* str, int len) { assert(len != 0); if(str == NULL) { return; } //当前已经处理好的结果字符串的尾指针 char* result_tail = str; //顺序扫描字符串的每个字符的指针 char* p = str; //存放p之前的字符是否是空格 bool is_pre_space=false; //忽略字符串最前面的空格 while (*p==' ' && len > 0) { p++; len--; } while (len > 0) { if (*p == ' ')//遇到空格 { if (!is_pre_space) { //保留空格 *result_tail = *p; result_tail++; } is_pre_space = true; p++; len--; } else if(*p == '\n')//遇到换行 { //前面有空格 if (is_pre_space) { result_tail--; } is_pre_space = false; //复制换行符 *result_tail = *p; result_tail++; p++; len--; //忽略换行后的空格 while (*p==' ' && len > 0) { p++; len--; } } else//其他字符 { //复制换行符 *result_tail = *p; result_tail++; p++; len--; is_pre_space = false; } } //移除尾部空格 if (is_pre_space) { result_tail--; } *result_tail = '\0'; } void main() { /*********************方法一************************************************/ //这样会崩溃的,因为常量字符串不可以改变!!!! //char *s = "abc d \n abc"; /*********************************************************************/ /***************************方法二******************************************/ //char *s = (char *)malloc(sizeof(100)); //gets(s); /***************但是这个不能输入 \n ******************/ /*****方法三,这个可以*****************************************/ char s[] = "abc d \n abc"; RemoveExtraSpace(s,strlen(s)); puts(s); }