In C, there is no built-in string type as in higher-level programming languages. Instead, strings are represented as arrays of characters.
Strings in C:
- String as a character array: In C, a string is typically an array of characters terminated by a null character (
'\0'
). This null character is used to mark the end of the string.
Example:
#include <stdio.h>
int main() {
char str[] = "Hello, World!"; // This is a string in C
printf("%s\n", str); // Prints: Hello, World!
return 0;
}
Here, "Hello, World!"
is a string literal, and when assigned to the char str[]
, it becomes an array of characters:
{'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'}
- String manipulation in C: C provides a set of standard library functions (defined in
<string.h>
) to manipulate character arrays, such asstrlen()
,strcpy()
,strcat()
,strcmp()
, etc.
Example of string manipulation:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = " World";
// Concatenate str2 to str1
strcat(str1, str2);
printf("%s\n", str1); // Output: Hello World
// Get length of str1
printf("Length of str1: %lu\n", strlen(str1)); // Output: 11
return 0;
}
Key points about strings in C:
- No built-in string type: Strings are arrays of characters.
- Null-terminated: Strings are terminated by a null character (
'\0'
), which marks the end of the string. - Manual memory management: You must manage memory manually (e.g., with
malloc()
orfree()
for dynamic strings).
C doesn’t have a string type like in higher-level languages (such as Python or Java). Instead, strings are just arrays of characters with special handling for the null terminator.