Welcome to our comprehensive guide on C String Manipulation! In this lesson, we'll dive deep into understanding and manipulating strings in C, a fundamental skill for every C programmer. Whether you're a beginner or an intermediate learner, this lesson is designed to help you master the art of string manipulation in C. Let's get started!
A string in C is an array of characters, followed by a null character \0. This null character signifies the end of the string.
char str[10] = "Hello";In the above example, the string "Hello" is an array of 6 characters, including the null character at the end.
To find the length of a string, we use the strlen() function.
#include <stdio.h>
#include <string.h>
int main() {
char str[10] = "Hello";
int len = strlen(str);
printf("Length of the string: %d\n", len);
return 0;
}To check if a string is empty, we can compare the length of the string to zero.
#include <stdio.h>
#include <string.h>
int main() {
char str[10] = "";
int len = strlen(str);
if(len == 0) {
printf("The string is empty.\n");
} else {
printf("The string is not empty.\n");
}
return 0;
}To concatenate two strings, we can use the strcat() function.
#include <stdio.h>
#include <string.h>
int main() {
char str1[10] = "Hello";
char str2[10] = "World";
char result[20];
strcat(str1, " ");
strcat(str1, str2);
strcpy(result, str1);
printf("Concatenated string: %s\n", result);
return 0;
}What is the output of the following code?
Stay tuned for our next lesson where we'll explore more advanced string manipulation techniques in C! 🚀