重复字母的代码如何工作?

时间:2017-08-28 10:41:10

标签: c function

我最近开始学习C,我有以下一段代码,我很难理解
基本上它是一个带字符串并显示它的函数, 重复每个字母字符与字母索引一样多次,然后换行。

#include <unistd.h>

int ft_is_alpha(char c)
{
  if ((c >= 'a') && (c <= 'z'))
    return (0);
  else
    return (1);

}

int ft_count(char c)
{
  int k;
  k = (c - 'a');
  return (k);
}

void ft_print(char **argv)
{
  int i;
  int j;
  i = 0;
  j = 0;
  while (argv[1][i])
  {
    if (ft_is_alpha(argv[1][i]))
    {
      write(1, &argv[1][i], 1);
    }
    else
    {
      while (j <= ft_count(argv[1][i]))
      {
        write(1, &argv[1][i], 1);
        j++;
      }
      j = 0;
    }
    i++;
  }
}

int main(int argc, char **argv)
{
  if (argc != 2)
  {
    write(1, "\n", 1);
    return (0);
  }
  ft_print(argv);
  write(1, "\n", 1);
  return (0);
}

结果:

 ./a.out "abcd"
    abbcccdddd 

我不明白的是ft_print如何工作以及代码在哪里乘以字母。
据我所知if the string is alpha it writes it letter by letterIf not - 在这里我遇到了j
另外,为什么它在while循环结束时使它0
有没有办法以某种方式逐行查看代码的作用?

3 个答案:

答案 0 :(得分:1)

这些字母乘以内部while循环:

  while (j <= ft_count(argv[1][i]))
  {
    write(1, &argv[1][i], 1);
    j++;
  }

ft_count()返回字母的字母索引。由于循环每次递增j,它将重复该索引的次数。

这也回答了你关于为什么它在循环之后分配j = 0;的第二个问题。这样下次将再次从0开始。如果不这样做,下一个字母只会通过其索引与前一个字母之间的差异重复。

答案 1 :(得分:0)

您可以在下面看到逐行说明。

while (argv[1][i])                       // While loop
{
  if (ft_is_alpha(argv[1][i]))          // Checks if the character is not in the range of aplhabets
                                        // Note - that the logic in this function is inverted as mentioned by others.
  {     
    write(1, &argv[1][i], 1);           // If not within 'a' to 'z' it will directly print the character.
  }
  else
  {
    while (j <= ft_count(argv[1][i]))   // This function returns the difference between the character and 'a'
                                        // e.g. for 'c' it will return 3    
    {
      write(1, &argv[1][i], 1);         // In the loop, this will write as the character as many times as j.
                                        // e.g. if the character is 'c' it will write ccc
                                        // if 'f' it will write ffffff
      j++;               
    }
    j = 0;
  }
  i++;
}

答案 2 :(得分:0)

误解代码的原因是函数ft_is_alpha

int ft_is_alpha(char c)
{
  if ((c >= 'a') && (c <= 'z'))
    return (0);
  else
    return (1);

}

在逻辑上定义错误。 (更确切地说,误解的原因是编写错误的代码。:))如果字符在1['a', 'z']范围内,该函数应该返回0

例如

int ft_is_alpha(char c)
{
    return c >= 'a' && c <= 'z';
}

在适当更改函数ft_print之后

void ft_print( char **argv )
{
    int i = 0;

    while ( argv[1][i] )
    {
        write( 1, &argv[1][i], 1 );

        if ( ft_is_alpha( argv[1][i] ) )
        {
            int n = ft_count( argv[1][i] );
            for ( int j = 0; j < n; j++ )
            {
                write(1, &argv[1][i], 1);
            }
        }
        i++;
    }
}

该程序将更具可读性和清晰度。

因此,如果下一个字符argv[1][i]位于['a', 'z']范围内,则会另外输出argv[1][i] - 'a'次。