Strings (char arrays)
Chapter: Strings in C
Strings are a fundamental concept in programming, representing sequences of characters. In C, strings are implemented as arrays of characters, terminated by a special null character (\0
). This chapter delves into all aspects of strings in C, including their declaration, initialization, operations, and common problems, with clear examples.
1. What is a String?
In C, a string is a collection of characters stored in a character array, with the null character (\0
) indicating the end of the string. This null character is crucial for distinguishing strings from plain arrays of characters.
Example:
A string "Hello"
is stored as:
'H' 'e' 'l' 'l' 'o' '\0'
Key Points:
Strings are null-terminated.
The null character (
\0
) must always be included, either explicitly or implicitly.Strings are immutable when defined as string literals.
2. Declaring and Initializing Strings
Strings can be declared in various ways:
2.1 Declaration
A string is declared as a character array:
char str[size];
2.2 Initialization Methods
Using a String Literal:
char str[] = "Hello";
Explicit Character Array:
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Uninitialized Array: Declare an array and assign characters later:
char str[10]; str[0] = 'H'; str[1] = 'i'; str[2] = '\0'; // Ensure null termination
3. Input and Output of Strings
3.1 Reading Strings
Strings can be read using functions like scanf
and fgets
.
Using
scanf
:char str[50]; scanf("%s", str); // Stops reading at spaces or newline
Warning:
scanf
does not handle spaces in strings.Using
fgets
(Preferred for safety):char str[50]; fgets(str, sizeof(str), stdin); // Reads spaces and stops at newline
3.2 Printing Strings
Use printf
with %s
for string output:
char str[] = "Hello, World!";
printf("%s\n", str);
4. String Operations
C provides standard library functions in <string.h>
for common string manipulations.
4.1 Find the Length of a String
Function: strlen
The strlen
function computes the length of a string (excluding the null character).
Example:
#include <string.h>
char str[] = "Hello";
int length = strlen(str); // length = 5
4.2 Copy a String
Function: strcpy
The strcpy
function copies a source string into a destination string.
Example:
#include <string.h>
char source[] = "Hello";
char destination[10];
strcpy(destination, source);
4.3 Concatenate Strings
Function: strcat
The strcat
function appends one string to the end of another.
Example:
#include <string.h>
char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2); // str1 becomes "Hello World"
4.4 Compare Strings
Function: strcmp
The strcmp
function compares two strings lexicographically:
Returns
0
if equal.Returns a positive value if the first string is greater.
Returns a negative value if the first string is smaller.
Example:
#include <string.h>
char str1[] = "Apple";
char str2[] = "Banana";
int result = strcmp(str1, str2); // result < 0
4.5 Reverse a String
C does not have a standard strrev
function. You can reverse a string manually:
Manual Example:
void reverseString(char str[]) {
int n = strlen(str);
for (int i = 0; i < n / 2; i++) {
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
}
}
4.6 Search for a Substring
Function: strstr
The strstr
function finds the first occurrence of a substring in a string.
Example:
#include <string.h>
char str[] = "Hello, World!";
char *substring = strstr(str, "World"); // substring points to "World!"
4.7 Tokenize a String
Function: strtok
The strtok
function splits a string into tokens based on a delimiter.
Example:
#include <string.h>
char str[] = "Hello,World,!";
char *token = strtok(str, ",");
while (token != NULL) {
token = strtok(NULL, ",");
}
5. Iterating Over Strings
Strings can be treated as arrays, allowing character-by-character traversal.
Example:
char str[] = "Hello";
for (int i = 0; str[i] != '\0'; i++) {
// Process str[i]
}
6. Common String Problems
Problem 1: Palindrome Check
A palindrome reads the same backward as forward.
Solution:
int isPalindrome(char str[]) {
int n = strlen(str);
for (int i = 0; i < n / 2; i++) {
if (str[i] != str[n - i - 1]) {
return 0;
}
}
return 1;
}
Problem 2: Count Vowels and Consonants
Solution:
void countVowelsConsonants(char str[], int *vowels, int *consonants) {
*vowels = *consonants = 0;
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
(*vowels)++;
} else {
(*consonants)++;
}
}
}
}
Problem 3: Count Character Occurrences
Solution:
int countOccurrences(char str[], char ch) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ch) {
count++;
}
}
return count;
}
7. Best Practices for Handling Strings
Always Null-Terminate: Ensure strings are properly terminated with
\0
.Use Safe Input Functions: Prefer
fgets
overgets
to prevent buffer overflows.Avoid Modifying String Literals: Modifying a string literal causes undefined behavior.
Allocate Sufficient Memory: Ensure arrays are large enough to store the string and the null character.
Summary
In this chapter, we explored strings in C, covering their structure, initialization, and essential operations like concatenation, comparison, and tokenization. With this foundation, you can efficiently work with strings to solve real-world text-processing problems. Remember to practice with the provided examples to strengthen your skills.
Last updated
Was this helpful?