【问题标题】:Count characters in an array of character strings?计算字符串数组中的字符?
【发布时间】:2018-04-20 21:43:15
【问题描述】:

给定一个字符串数组,例如...

char *example[] = {"s", "ss", "sss"};

如何编写一个函数来计算数组中字符的总数,包括终止字符,而不使用 strlen() 等的标准库。

以下是我的尝试

int countChars(char *array[], int len)
{
    int total = 0, count = 0;


    for (int i = 0; i < len; i++)
    {
        if (array[i] != NULL)
        {
            while (*array[i] != '\0') {
                count++;
            }
            count++;
        }
        total += count;
    }

    return total;
}

关于 char *array[] 如何实际用于访问的解释将不胜感激。我相信它应该是一个指向字符串的指针数组。

【问题讨论】:

  • 好吧,你有什么问题?我看到的明显错误是您没有在每个单词之间重置count
  • 看来if (array[i] != NULL)没有任何意义。
  • 如果数组中的字符串已被删除。
  • 如果您计算 字节,这很容易。如果你想计算字符,它可能会非常复杂。 (多字节编码,组合字符,...)

标签: c string


【解决方案1】:

是的,char *array[] = {"aa", "bb", "cc"} 是一个指向字符串的指针数组。

  • array[0] 指向 "aa"
  • array[1] 指向 "bb"
  • array[2] 指向"cc"

你可能想要这个:

int countChars(char *array[], int len)
{
  int count = 0;

  for (int arrayindex = 0; arrayindex < len; arrayindex++)
  {
    const char *stringptr = array[arrayindex];
                                // stringptr will point successively
                                // to "s", to "ss" and to "sss"

    while (*stringptr++)
      count++;                  // increment count until NUL character encountered
    count++;                    // one more for NUL character
  }

  return count;
}

int main() {
  char *example[] = { "s", "ss", "sss" };

  int x = countChars(example, 3);   // x contains 9 after the call to countChars
                                    // that is 2 + 3 + 4
}

您可以使用sizeof(example) / sizeof(example[0]),而不是硬编码3

【讨论】:

    【解决方案2】:

    由于您的数组包含字符串常量,您应该使用const 声明它:

    const char *example[3];
    

    如果没有const,如果您尝试将字符分配给example[i][j],编译器不会发出警告。同理,形参也应该用const声明。

    对于没有副作用的纯函数,最好命名它以便它反映结果。因此,我会使用 charCount 而不是 countChars(或者可能是 totalLength)。重点应该放在一个名词上(即countlength)。

    这是我的解决方案:

    #include <stdio.h>
    
    #define LEN(a) (sizeof (a) / sizeof (a)[0])
    
    static int CharCount(const char *strings[], int len)
    {
        int result, i, j;
    
        result = 0;
        for (i = 0; i < len; i++) {
            j = 0;
            while (strings[i][j] != '\0') {
                result++;
                j++;
            }
        }
        return result;
    }
    
    
    int main(void)
    {
        const char *strings[] = { "s", "ss", "sss" };
    
        printf("character count: %d\n", CharCount(strings, LEN(strings)));
    }
    

    长度宏LEN非常方便,是处理数组长度最不容易出错的方法。

    【讨论】:

      【解决方案3】:

      您需要在 for 循环内为每个处理过的字符串重新初始化变量 count,并在 while 循环内增加表达式 *array[i]

      函数的返回类型最好是size_tsize_t 是标准 C 函数 strlen 和运算符 sizeof 返回的类型)

      函数看起来就像演示程序中显示的那样。

      #include <stdio.h>
      
      size_t countChars( const char *array[], size_t n )
      {
          size_t count = 0;
      
          while ( n-- )
          {
              if ( array[n] )
              {
                  size_t i = 0;
                  do { ++count; } while ( array[n][i++] );
              }
          }
      
          return count;
      }
      
      int main(void) 
      {
          const char * example[] = { "s", "ss", "sss" };
      
          printf( "%zu\n", countChars( example, sizeof( example ) / sizeof( *example ) ) );
      
          return 0;
      }
      

      程序输出为

      9
      

      这个数组的每个元素

      char *example[] = {"s", "ss", "sss"};
      

      类型为char *,是指向相应字符串文字的第一个字符的指针。

      【讨论】:

        【解决方案4】:
        • 您必须增加索引以考虑每个字符。

        类似这样的:-

        for (int i = 0; i < len; i++)
        {
            if (array[i] != NULL)
            {
                int j=0,count=0;
                while (array[i][j++] != '\0') {
                    count++;
                }
                total += count;     
            }
        
        }
        
        • 还可以在所有计算结束时重置count 或添加到total

        作为第二个问题的答案:-


        char* array[] 基本上表示每个指向的数组指针 到你初始化它的字符串文字。

        所以一旦你使用array[i],你现在应该认为它什么都不是 除了指向字符串文字的指针。

        【讨论】:

        • count 在 if 块中定义。 total += count; :在超出范围的情况下使用 count。还包括终止字符
        • @BLUEPIXY.:答案正确地检测到了问题。但是感谢您的帮助
        猜你喜欢
        • 2021-01-24
        • 1970-01-01
        • 2018-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-06
        • 2016-05-24
        相关资源
        最近更新 更多