Programming in C

(Barry) #1

200 Chapter 10 Character Strings


int stringLength (const char string[])
{
int count = 0;

while ( string[count] != '\0' )
++count;

return count;
}

int main (void)
{
int stringLength (const char string[]);
const char word1[] = { 'a', 's', 't', 'e', 'r', '\0' };
const char word2[] = { 'a', 't', '\0' };
const char word3[] = { 'a', 'w', 'e', '\0' };

printf ("%i %i %i\n", stringLength (word1),
stringLength (word2), stringLength (word3));

return 0;
}

Program 10.2 Output
5 2 3

The stringLengthfunction declares its argument as a constarray of characters because
it is not making any changes to the array, merely counting its size.
Inside the stringLengthfunction, the variable countis defined and its value set to 0.
The program then enters a whileloop to sequence through the stringarray until the
null character is reached.When the function finally hits upon this character, signaling the
end of the character string, the whileloop is exited and the value of countis returned.
This value represents the number of characters in the string, excluding the null character.
You might want to trace through the operation of this loop on a small character array to
ver ify that the value of countwhen the loop is exited is in fact equal to the number of
characters in the array, excluding the null character.
In the mainroutine, three character arrays,word1,word2,and word3,are defined.The
printffunction call displays the results of calling the stringLengthfunction for each of
these three character arrays.

Program 10.2 Continued
Free download pdf