- Declaration
char name[20]; /* Name can have as many as 19 characters and the
null terminator */
char social_security[12]; /* 123-45-6789 and the null terminator */
- Declaration and Initialization - Initialization is NOT assignment.
char name[20] = "John";
char doggie[5] = {'S', 'p', 'o', 't', '\0'};
- Output
char name[10] = "Thomas";
printf("\nYour name is %s", name);
puts("\nYour name is ");
puts(name);
Both the printf() and the puts() output whatever is stored in name beginning
with the first location and outputting one character at a time until a null
terminator is found. The null terminator is automatically included in the
literal strings "\nYour name is %s" used by printf() and "\nYour name is "
used by puts.
- Input
- Comparison
int int_value;
char string1[10] = "first", string2[10] = "second";
int_value = strcmp(string1, string2);
C's string comparison functions returns 0 if the strings are the same, a value
less than 0 if the first string1 is alphabetically before string2 and a value
greater than 0 if string2 is alphabetically before string1. In this example,
the value in int_value is less than 0.
- Copy
strcpy(string1, string2);
This procedure copies the value of string2 into string1. It is up to the
programmer to make sure that string1 is large enough to hold string2.
- Concatenation
strcat(string1, string2);
The value in string2 is "added" to the value in string1. It is the
responsibility of the programmer to make sure that string1 is large enough
to hold the combined string. Example: Assume string1 is "hello" and that
string2 is "goodbye". The new value of string1 after concatenation is
"hellogoodbye".
- Finding the length of a string
int_value = strlen(string);
C provides the strlen() function which returns an integer representing the
number of characters in the string. The null terminator is not counted. For
example: "John" is length 4, "Smith" is length 5, "Tom Smith" is length 9.