๐ C Strings – Introduction to String Handling in C
A string in C is an array of characters terminated by a special null character \0. Strings are used to store text data in C programs. In this tutorial, we will learn how to declare, initialize, and manipulate strings in C.
๐น Declaring a String
A string is declared as an array of characters. The size of the array must be large enough to hold the string, including the null terminator \0.
๐ Example 1: Declaring a String
Here’s an example of declaring a string:
#include <stdio.h>
int main() {
char str[6] = "Hello"; // Declaring a string with 5 characters + null terminator
printf("String: %s\n", str); // Printing the string
return 0;
}
๐น Initializing a String
You can initialize a string at the time of declaration. When initializing, you can either provide the string literal or an array of characters, ensuring there is space for the null terminator.
๐ Example 2: Initializing a String
Here’s an example of initializing a string:
#include <stdio.h>
int main() {
char str[] = "Hello, World!"; // The size is automatically determined based on the string
printf("String: %s\n", str); // Printing the string
return 0;
}
๐น Accessing Individual Characters
In C, strings are arrays of characters, so you can access individual characters in a string using array indexing.
๐ Example 3: Accessing Individual Characters
In this example, we access and print individual characters of a string:
#include <stdio.h>
int main() {
char str[] = "Hello";
// Accessing and printing individual characters
for (int i = 0; str[i] != '\0'; i++) {
printf("Character at position %d: %c\n", i, str[i]);
}
return 0;
}
๐ฏ Key Points about Strings in C
- A string in C is an array of characters terminated by
\0. - Strings can be declared as arrays of characters, and they can be initialized with string literals.
- You can access individual characters in a string using array indexing.
- In C, strings are treated as arrays, and you must be mindful of the null terminator
\0.
๐ก Practice Challenge
Try modifying the string by changing its contents or accessing specific characters in the string. Experiment with different string operations and observe how they affect the output!