在C语言中,如何将字符串从不确定的用户输入中分离出来?

在C语言中,如何将字符串从不确定的用户输入中分离出来?,c,input,C,Input,我正在尝试从用户处获取程序的输入,该输入具有以下条件: 用户将输入一个字符串-foo或bar,但字符串前后可以有尽可能多的空格 然后,用户将输入另一个字符串,可以是任何内容-例如,Jacob McQueen或带有4个单词的随机字符串 因此,如果用户输入-\uuuuuuuuuuuufoo\uuuuuuuuujacob McQueen “\”表示空格字符 我需要把foo和Jacob McQueen这两条线分开 我应该如何在C中执行此操作 int extract(const char s, char

我正在尝试从用户处获取程序的输入,该输入具有以下条件:

用户将输入一个字符串-foo或bar,但字符串前后可以有尽可能多的空格

然后,用户将输入另一个字符串,可以是任何内容-例如,Jacob McQueen或带有4个单词的随机字符串

因此,如果用户输入-\uuuuuuuuuuuufoo\uuuuuuuuujacob McQueen

“\”表示空格字符

我需要把foo和Jacob McQueen这两条线分开

我应该如何在C中执行此操作

int extract(const char s, char **key_ptr, char **rest_ptr) {
   *key_ptr  = NULL;
   *rest_ptr = NULL;

   const char *start_key;
   const char *end_key;
   const char *start_rest;

   // Skip leading spaces.
   while (*s == ' ')
      ++s;

   // Incorrect format.
   if (!*s)
      goto ERROR;

   start_key = s;

   // Find end of word.
   while (*s && *s != ' ')
      ++s;

   // Incorrect format.
   if (!*s)
      goto ERROR;

   end_key = s;

   // Skip spaces.
   while (*s == ' ')
      ++s;

   /* Uncomment if you want to disallow zero-length "rest".
   ** // Incorrect format.
   ** if (!*s)
   **    goto ERROR;
   */

   start_rest = s;

   const size_t len_key = end_key-start_key;
   *key_ptr = malloc(len_key+1);
   if (*key_ptr == NULL)
      goto ERROR;

   memcpy(*key_ptr, start_key, len_key);
   (*key_ptr)[len_key] = 0;

   *rest_ptr = strdup(start_rest);
   if (*rest_ptr == NULL)
      goto ERROR;

   return 1;

ERROR:
   free(*key_ptr);  *key_ptr  = NULL;
   free(*rest_ptr); *rest_ptr = NULL;
   return 0;
}
用法:

char *key;
char *rest;
if (extract(s, &key, &rest)) {
   printf("Found [%s] [%s]\n", key, rest);
   free(key);
   free(rest);
} else {
   printf("No match.\n");
}

您可以使用scanf来完成重物搬运。“%s”将读取第一个令牌foo/bar,“%[^\n]”将把所有其他内容(直到新行)读取到word2中。长度是任意的

   char word1[10], word2[100] ;
   if ( scanf("%9s %99[^\n]", word1, word2) == 2 ) {
      // Do something with word1, word2
   } ;


如果您需要无限长度,请考虑使用“M”长度修改器用于MalcOLED字符串

注释:“m”修饰符仅为不可移植的Linux,而M是较早版本的glibc@DavidRankin-在POSIX中引入了“m”修饰符作为标准。看见