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

发布于 2024-08-26 22:52:47 字数 323 浏览 5 评论 0原文

我有一些这样的输入:

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

我需要像这样清理它:

"aaaaa bbb cccccc ddddd neeee"

基本上:

  • 修剪字符串开头和结尾的所有空格
  • 删除所有新行
  • 当有多个空格时删除所有空格,但始终在之间留一个空格有

没有简单的方法可以做到这一点,或者我必须逐个字符地处理字符串并将适当的字符复制到不同的变量?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风启觞 2024-09-02 22:52:47

假设您无法就地修改字符串,

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);

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);
债姬 2024-09-02 22:52:47

您可以使用 strtok 对字符串进行词法标记,并用“ \r\n\t”分隔。
这将使您的工作更加轻松。

You could use strtok to lexically tokenize the string, delimit with " \r\n\t".
This will make your job easier.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文