String
A string is a sequence of characters stored in contiguous memory locations, terminated by a null character '\0'
. Strings in C are represented as arrays of characters (char[]
) where each element of the array holds a single character. The null character marks the end of the string.
Here are some key characteristics of strings in C:
- Null Termination: C strings are null-terminated, meaning that the null character
'\0'
is used to mark the end of the string. This character is automatically appended to the end of string literals. - String Literals: A string literal is a sequence of characters enclosed in double quotes (
"
). For example,"hello"
is a string literal representing the string “hello”. String literals are automatically null-terminated. - Character Array: Strings in C are typically represented as arrays of characters (
char[]
). Each element of the array holds a single character, and the last element is always the null character to signify the end of the string. - Character Pointer: Strings can also be represented using pointers to characters (
char*
). A pointer to the first character of the string is sufficient to access the entire string. - Standard Library Functions: C provides a set of standard library functions for working with strings, such as
strcpy
,strcat
,strlen
,strcmp
, etc. These functions are declared in thestring.h
header file.
Example :
#include <stdio.h>
#include <string.h>
int main() {
// String declaration and initialization
char str1[] = "hello";
char str2[6] = {'h', 'e', 'l', 'l', 'o', '\0'};
char* str3 = "world";
// Print strings
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
printf("str3: %s\n", str3);
// String length
printf("Length of str1: %ld\n", strlen(str1));
// String concatenation
strcat(str1, " world");
printf("Concatenated string: %s\n", str1);
// String comparison
if (strcmp(str1, str3) == 0) {
printf("str1 and str3 are equal\n");
} else {
printf("str1 and str3 are not equal\n");
}
return 0;
}
Output:
str1: hello
str2: hello
str3: world
Length of str1: 5
Concatenated string: hello world
str1 and str3 are equal