Strings in C are fundamental yet distinct from other programming languages. In C, a string is essentially an array of characters, ending with a null character ('\0'
) that signals the end of the string. Unlike higher-level languages with dedicated string data types, C relies on character arrays to handle text. This introduces unique challenges and requires a good understanding of memory management.
In this blog, we’ll explore how to declare and initialize strings in C, covering character arrays and string literals. We’ll also dive into essential string operations like finding the length, copying, concatenation, comparison, and tokenization. For those new to C or looking to solidify their understanding of string handling, this guide will offer clear explanations and practical examples to help you confidently manage strings in your C programs.
In C, a string is essentially an array of characters, ending with a special null character (‘\0’) to indicate the end of the string.
C does not have a built-in string data type like other high-level languages, so strings are usually handled using character arrays.
Declaring and Initializing a String
A string can be declared as an array of characters or using a string literal.
1. Using Character Array:
char str[20]; // Declare a string with a maximum size of 20 characters
2. Using String Literal:
char str[] = “Hello, World!”; // Automatically sizes the array based on the length of the string
String Operations
Some common string operations in C include:
#include <string.h>
size_t len = strlen(str); // Returns the length of the string
2. Copying Strings (strcpy):
char source[] = “Hello”;
char destination[20];
strcpy(destination, source); // Copies “Hello” into destination
3. Concatenating Strings (strcat):
char str1[30] = “Hello, “;
char str2[] = “World!”;
strcat(str1, str2); // Appends “World!” to “Hello, “
4. Comparing Strings (strcmp):
if (strcmp(str1, str2) == 0) {
printf(“Strings are equal\n”);
} else {
printf(“Strings are not equal\n”);
}
5. Copying a specified number of characters (strncpy):
strncpy(destination, source, 5); // Copies the first 5 characters of ‘source’ to ‘destination’
6. Finding a Character (strchr):
char *ptr = strchr(str, ‘o’); // Finds the first ‘o’ in the string
7. Tokenizing a String (strtok):
char str[] = “apple,banana,cherry”;
char *token = strtok(str, “,”);
while (token != NULL) {
printf(“%s\n”, token);
token = strtok(NULL, “,”);
}
Example Code
Here’s a simple example of declaring, manipulating, and printing a string in C:
#include <stdio.h>
#include <string.h>
int main() {
char greeting[] = “Hello, World!”;
// Print the string
printf(“Greeting: %s\n”, greeting);
printf(“Length: %lu\n”, strlen(greeting));
// Modify the string
greeting[7] = ‘C’;
printf(“Modified Greeting: %s\n”, greeting);
return 0;
}
Important Notes:
Indian Institute of Embedded Systems – IIES