Secernere
Secernere

Reputation: 63

Count characters in an array of character strings?

Given an array of character strings such as...

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

How can I write a function to count the total number of chars in the array including the terminating characters, without using the standard library for strlen() etc.

Follows is my attempt

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;
}

An explanation on how char *array[] actually works for access wold be appreciated. I believe that it is supposed to be an array of pointers to strings.

Upvotes: 1

Views: 15311

Answers (4)

Jabberwocky
Jabberwocky

Reputation: 50912

Yes char *array[] = {"aa", "bb", "cc"} is an array of pointers to strings.

  • array[0] points to "aa"
  • array[1] points to "bb"
  • array[2] points to "cc"

You probably want this:

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
}

Instead of hard coding 3 you could use sizeof(example) / sizeof(example[0]).

Upvotes: -1

August Karlstrom
August Karlstrom

Reputation: 11377

Since your array contains string constants you should declare it with const:

const char *example[3];

Without const the compiler will not warn you if you try to assign a character to example[i][j]. For the same reason the formal parameter should also be declared with const.

For a pure function with no side effects it is better to name it so that it reflects the result. Therefor I would use charCount instead of countChars (or maybe totalLength). The focus should be on a noun (namely count or length).

Here is my solution:

#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)));
}

The length macro LEN is very convenient and is the least error prone way to handle array lengths.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

You need to reinitialize the variable count inside the for loop for each processed string and to increase the expression *array[i] inside the while loop.

Also it is better when the function has the return type size_t (size_t is the type that is returned by the standard C function strlen and by the operator sizeof)

The function can look as it is shown in the demonstrative program.

#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;
}

The program output is

9

Each element of this array

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

has type char * and is a pointer to the first character of the corresponding string literal.

Upvotes: 0

user2736738
user2736738

Reputation: 30936

  • You have to increment the index to consider each of the character.

Something like this:-

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

}
  • Also reset the count or add to total at the end of all the calculation.

As an answer to your second question:-


char* array[] is basically denoting an array pointers each pointing to the string literals with which you initialized it.

So once you use array[i] you should now think that it is nothing other than a pointer to a string literal.

Upvotes: 2

Related Questions