In C programming, a string is defined as a one-dimensional array of characters terminated by a null character (\0). The null character is essential because it marks the end of the string in memory.
char string_name[size];
When declaring a string, the size must be large enough to hold the characters plus the null terminator. For example, to store "HELLO", you need an array of at least 6 characters.
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};char str[] = "Hello"; (The compiler automatically adds \0 at the end).char str[10] = "Hello"; (The remaining 4 indices are filled with null characters).C provides several ways to perform Input and Output (I/O) operations on strings.
scanf("%s", str); - Reads a string but stops at the first whitespace (space, tab, or newline).gets(str); - Reads a full line of text including spaces until the Enter key is pressed. (Note: Be careful as it does not check for buffer overflow).printf("%s", str); - Displays the string on the screen.puts(str); - Displays the string and automatically adds a newline character at the end.Processing involves manipulating the characters within the string using loops or pointers. Since a string is an array, you can access individual characters using their index.
Example: Counting Vowels
To process a string, you typically use a loop that runs until it encounters the '\0' character.
for(int i = 0; str[i] != '\0'; i++) {
// Process each character str[i]
}
The <string.h> header file provides a powerful set of functions to simplify string operations.
| Function | Purpose | Example Usage |
|---|---|---|
| strlen() | Returns the length of the string (excluding \0). | len = strlen("Hello"); // Result: 5 |
| strcpy() | Copies one string into another. | strcpy(dest, src); |
| strcat() | Concatenates (joins) two strings. | strcat(s1, s2); |
| strcmp() | Compares two strings alphabetically. | if(strcmp(s1, s2) == 0) // Identical |
| strrev() | Reverses the string characters. | strrev(str); |
#include <string.h> when using functions like strlen or strcpy.'\0' as a string. Functions like printf will keep reading memory until they find a zero, causing "garbage" output.scanf("%s", name) to read a name with a space (e.g., "John Doe"). It will only store "John".str1 = str2; to copy strings. In C, you must use strcpy() for this operation.Q: What is the difference between 'A' and "A"?
A: 'A' is a single character (1 byte), while "A" is a string containing 'A' and '\0' (2 bytes).
Q: Is the null character included in the length returned by strlen()?
A: No, strlen() only counts the visible characters.
Q: Why is gets() considered dangerous?
A: It does not check the size of the array, so if a user enters more characters than the array can hold, it overwrites other memory (buffer overflow).