【问题标题】:String from user input that gets converted into a letter pattern.来自用户输入的字符串,它被转换为字母模式。
【发布时间】:2017-04-22 23:20:15
【问题描述】:

因为我的第一篇文章不好所以重新发布。我有一个问题,我不确定该怎么做。我知道我要进行的过程,但不完全确定如何将字符串扫描到数组中,以便将每个字符/整数扫描到数组的独立元素中。我将发布问题和到目前为止的代码,我们将不胜感激。

问题:

假设我们有如下模式:([n][letter])+ 其中 n 是整数,字母是 a-z 中的小写字母之一。例如,2a 和 3b 是基于我们的模式的有效表达式。此外,模式末尾的“+”表示我们至少有一个表达式(字符串)或多个表达式附加。例如,2a4b 是另一个与模式匹配的有效表达式。在这个问题中,我们想将这些有效的表达式转换为一个字母重复 n 次的字符串。

o 从用户读取一个表达式(字符串)并在输出中打印该表达式的转换版本。

o 检查输入表达式是否有效。例如,2ab 不是一个有效的表达式。如果表达式无效,则在输出中打印“Invalid”并要求用户输入另一个表达式。

o 样本输入 1 = “2a”,输出 = aa

o 样本输入 2 = “2a3b”,输出 = aabbb

o 如果您简要说明您可以使用什么概念或理论来检查表达式是否有效,您将获得额外的分数。

到目前为止我所拥有的:

#include <stdio.h>

int main()

{
    int size, i, j;
    char pattern[20];
    char vowel[20];
    int count[20];
    printf("Please enter your string: ");
    gets(pattern);
    size = strlen(pattern);

    for(i=0; i<size; i++)
        if((i+1)%2  == 0)
            vowel[i] = pattern[i];
        else if((i+1)%2 != 0)
            count[i] = pattern[i];

    for(i=0; i<size/2; i++);
        for(j=0; j<count[i]; j++)
            printf("%s", vowel[i]);
}

【问题讨论】:

  • 从不使用gets。它已从标准中删除,任何现代编译器/库都会至少发出警告。使用fgets

标签: c arrays string


【解决方案1】:

我假设您想在 stderr 上写入“invalid\n”字符串。如果不只是更改给定写入的文件描述符。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define MAX_INPUT_SIZE 20

int
check_input(char *input)
{
  while (*input)
    {
      if (*input < '0' || *input > '9')
        {
          write(2, "invalid\n", 8);
          return 1;
        }
      while (*input >= '0' && *input <= '9')
        input++;
      if (*input < 'a' || *input > 'z')
        {
          write(2, "invalid\n", 8);
          return 1;
        }
      input++;
    }
  return 0;
}

void
print_output(char *input)
{
  int i;

  while (*input)
    {
      i = atoi(input);
      while (*input >= '0' && *input <= '9')
        input++;
      for (; i > 0; i--)
        write(1, input, 1);
      input++;
    }
  write(1, "\n", 1);
}

int
main()
{
  char input[MAX_INPUT_SIZE];

  do
    {
      printf("Please enter your string: ");
      fgets(input, MAX_INPUT_SIZE, stdin);
      input[strlen(input) - 1] = '\0';
    }
  while (check_input(input));
  print_output(input);
  return 0;
}

【讨论】:

    【解决方案2】:

    步骤如下:

    1. 阅读模式
    2. 检查模式是否有效
    3. 生成输出

    由于未指定输入长度,您必须假设最大长度。 另一个假设是n 是个位数。

    现在您可以使用fgets() 读取整个表达式,或者逐个字符地读取它。 后者允许您在阅读时检查有效性。

    为了方便起见,让我们使用fgets(),以防表达式需要存储以备后用。

    char exp[100]; // assuming at most 50 instances of ([n][letter])
    int len;
    
    printf("Input: ");
    fgets(exp, 100, stdin);
    len = strlen(exp) - 1;    // Discard newline at end
    

    空输入无效。有效的表达式长度也应该是偶数。

    if (len == 0 || len%2 != 0) {
        printf("Invalid-len\n");
        return 1;
    }
    

    现在解析表达式并将数字和字母分别存储在两个数组中。

    char nums[50], letters[50];
    invalid = 0;
    for (i = 0, j = 0; i < len; i += 2, j++) {
        if (exp[i] >= '1' && exp[i] <= '9') {
            nums[j] = exp[i] - '0';
        } else {
            invalid = 1;
            break;
        }
    
        if (exp[i+1] >= 'a' && exp[i+1] <= 'z') {
            letters[j] = exp[i+1];
        } else {
            invalid = 1;
            break;
        }
    }
    

    请注意,在每次迭代中,如果第一个字符不是数字或第二个字符不是字母,则表达式被认为是无效的。 如果发现表达式无效,则什么也不做。

    if (invalid) {
        printf("Invalid\n");
        return 1;
    }
    

    对于有效的表达式,运行嵌套循环来打印输出。
    外部循环对每个 ([n][letter]) 模式进行迭代。 内部循环打印 n字母

    printf("Output: ");
    for (i = 0; i < len/2; i++) {
        for (j = 0; j < nums[i]; j++)
            printf("%c", letters[i]);
    }
    

    这是解决此类问题的一种相当幼稚的方法。最好使用正则表达式。 C 标准库不支持正则表达式。但是在类 Unix 系统上,您可以使用 POSIX regular expressions

    【讨论】:

      【解决方案3】:

      喜欢这个

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      #include <ctype.h>
      #include <stdbool.h>
      
      #define prompt "Please enter your string: "
      
      void occurs_error(const char *src, const char *curr){
          printf("\nInvalid\n");
          printf("%s\n", src);
          while(src++ != curr){
              putchar(' ');
          }
          printf("^\n");
      }
      
      bool invalid(char *pattern){
          char *p = pattern;
          while(*p){
              if(!isdigit((unsigned char)*p)){//no number
                  occurs_error(pattern, p);
                  break;
              }
              strtoul(p, &p, 10);
              if(!*p || !islower((unsigned char)*p)){//no character or not lowercase
                  occurs_error(pattern, p);
                  break;
              }
              ++p;
          }
          return *p;
      }
      
      int main(void){
          char pattern[20];
      
          while(fputs(prompt, stdout), fflush(stdout), fgets(pattern, sizeof pattern, stdin)){
              pattern[strcspn(pattern, "\n")] = 0;//chomp newline
      
              char *p = pattern;
              if(invalid(p)){
                  continue;
              }
              while(*p){
                  int n = strtoul(p, &p, 10);
                  while(n--)
                      putchar(*p);
                  ++p;
              }
              puts("");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 2020-07-05
        • 2010-10-26
        • 1970-01-01
        相关资源
        最近更新 更多