C: Strings - String Operations
(Page 3 of 6 )
There are many string functions in C, and we will discuss a few of them here, starting with the strlen() function. Before we do though, be sure to include the <string.h> library.
Strlen()
If you want to count the amount of characters in a string, you can use the strlen() function.
#include <stdio.h>
#include <string.h>
int main ()
{
char name[80];
int length;
printf("Enter your name: ");
gets_s (name);
length=strlen(name);
printf("nThe name %s contains %d characters, including
spaces.n",name, length);
return(0);
}
This program creates an array capable of holding 79 characters called “name,” and a variable named length. It then prints some text asking the user to enter their name and stores the input in the name array. Next, we use the strlen() function to count the number of characters (including spaces) in the name array, and store it in the variable length. Finally, we print some text displaying the user's name and how many characters are in their name. If the user had input Aunt Jemima as their name, this would be the result:
Enter your name: Aunt Jemima
The name Aunt Jemima contains 11 characters, including spaces.
Next: Strcat() >>
More BrainDump Articles
More By James Payne