如何在C中将字符串与不确定的用户输入分开?

我正在尝试从用户那里获取程序的输入,并且输入具有以下条件:

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

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

因此,如果用户输入-______foo___Jacob McQueen

(“ _”表示空格)

我需要将字符串“ foo”和“ Jacob McQueen”分开。

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

libailiang 回答:如何在C中将字符串与不确定的用户输入分开?

您可以使用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'长度修饰符

,
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");
}
本文链接:https://www.f2er.com/3155394.html

大家都在问