C String Manipulation Examples 🎯

beginner
22 min

C String Manipulation Examples 🎯

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!

Understanding Strings in C 📝

A string in C is an array of characters, followed by a null character \0. This null character signifies the end of the string.

c
char str[10] = "Hello";

In the above example, the string "Hello" is an array of 6 characters, including the null character at the end.

Basic String Operations 💡

Length of a String

To find the length of a string, we use the strlen() function.

c
#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; }

Checking if a String is Empty

To check if a string is empty, we can compare the length of the string to zero.

c
#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; }

Concatenating Strings

To concatenate two strings, we can use the strcat() function.

c
#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; }

Quiz Time 💡

Quick Quiz
Question 1 of 1

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! 🚀