In this tutorial, we will learn about strings in C. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
A string in C is a sequence of characters terminated by a null character ('\0'). Strings in C are typically represented as arrays of characters.
Strings can be created in C using character arrays:
char str[] = "Hello, world!";
Alternatively, you can use a pointer to a character:
char *str = "Hello, world!";
<stdio.h>
header file.printf
.#include <stdio.h>
int main() {
char str[] = "Hello, world!";
printf("%s", str);
return 0;
}
Hello, world!
<stdio.h>
header file.#include <stdio.h>
int main() {
char str[] = "Hello";
printf("%c\n", str[0]); // Accessing using array indexing
printf("%c\n", str[1]);
return 0;
}
H e
<stdio.h>
header file.#include <stdio.h>
int main() {
char str[50] = "Hello";
str[0] = 'J'; // Modifying individual character
strcat(str, " World!"); // Appending new characters using strcat
printf("%s", str);
return 0;
}
Jello World!
<stdio.h>
and <string.h>
header files.strcat
function.#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[] = " World!";
strcat(str1, str2); // Concatenating strings
printf("%s", str1);
return 0;
}
Hello World!
<stdio.h>
and <string.h>
header files.strstr
function to find a substring.#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char *pos = strstr(str, "world"); // Finding substring
if (pos != NULL) {
printf("Found 'world' at position: %ld", pos - str);
} else {
printf("Substring not found");
}
return 0;
}
Found 'world' at position: 7
<stdio.h>
and <string.h>
header files.strlen
function to get the length of the string.#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
printf("Length of the string: %ld", strlen(str)); // Getting string length
return 0;
}
Length of the string: 13