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

2. Reading and Writing Strings

C provides several ways to perform Input and Output (I/O) operations on strings.

Reading Strings

Writing Strings

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

Exam Tips
Common Mistakes
Frequently Asked Questions

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).