Unit 9: Strings
Table of Contents
1. Defining and Initializing Strings
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.
Declaration
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.
Initialization Methods
- Character-by-character:
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'}; - String Literal:
char str[] = "Hello";(The compiler automatically adds \0 at the end). - With Size:
char str[10] = "Hello";(The remaining 4 indices are filled with null characters).
2. Reading and Writing Strings
C provides several ways to perform Input and Output (I/O) operations on strings.
Reading Strings
- scanf():
scanf("%s", str);- Reads a string but stops at the first whitespace (space, tab, or newline). - gets():
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).
Writing Strings
- printf():
printf("%s", str);- Displays the string on the screen. - puts():
puts(str);- Displays the string and automatically adds a newline character at the end.
3. Processing of Strings
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] } 4. String Library Functions
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); |
5. Exam Focus Enhancements
- The +1 Rule: Always remember to allocate space for the null terminator. If your string has 5 characters, your array size must be at least 6.
- Header File: Never forget to include
#include <string.h>when using functions likestrlenorstrcpy. - strcmp Return Values: 0 means equal, positive means s1 > s2, and negative means s1 < s2.
- No Null Terminator: Treating a character array without a
'\0'as a string. Functions likeprintfwill keep reading memory until they find a zero, causing "garbage" output. - scanf Limitation: Using
scanf("%s", name)to read a name with a space (e.g., "John Doe"). It will only store "John". - String Assignment: Attempting
str1 = str2;to copy strings. In C, you must usestrcpy()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).