繁体   English   中英

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

[英]How do I separate strings from uncertain user input in C?

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

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

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

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

('_' 表示空格字符)

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

我应该如何在 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
   } ;

如果您需要无限长度,请考虑对 malloced 字符串使用“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");
}

暂无
暂无

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

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