简体   繁体   English

从C中的字符串中删除空格和换行符

[英]Stripping blank spaces and newlines from strings in C

I have some input like this: 我有一些这样的输入:

"  aaaaa      bbb \n cccccc\n ddddd \neeee   "

And I need to sanitize it like this: 我需要像这样对它进行消毒:

"aaaaa bbb cccccc ddddd neeee"

Basically: 基本上:

  • Trim all blank spaces at the beginning and end of the string 修剪字符串开头和结尾的所有空格
  • Strip all new lines 删除所有新行
  • Strip all spaces when there is more than one, but always leave ONE space between words 如果有多个空格,请去除所有空格,但单词之间始终保留一个空格

Is there any easy way to do this or I'll have to process the string, char by char and copy the appropriate chars to a different variable? 有什么简单的方法可以执行此操作,否则我将必须逐个字符处理字符串并将相应的字符复制到其他变量中?

Assuming you cannot modify string in place, 假设您无法就地修改字符串,

void splcpy(char *s, char *m){ //s is the unmodified string
  int word = -1; //keeps track what was stored in last loop
  while(*s){  //until it ends
    if(!isspace(*s)){
      if(word==0)  *m++ = ' '; //if last char was space, add space
      *m++ = *s++;
       word = 1;
    }
    else{
      if(word == 1)   word = 0; //if last char was !space
      while(isspace(*s++)); //consume all space until end
    }
  }
  *m = '\0'; //end the string nicely
}

char *input = "  aaaaa      bbb \n cccccc\n ddddd \neeee   ";
char *modified = malloc(sizeof(char) * strlen(input));

splcpy(input, modified);

You could use strtok to lexically tokenize the string, delimit with " \\r\\n\\t". 您可以使用strtok词汇化字符串化字符串,并用“ \\ r \\ n \\ t”分隔。 This will make your job easier. 这将使您的工作更加轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM