Welcome to our C String Introduction lesson! In this tutorial, we'll dive into the world of strings in C programming, teaching you how to create, manipulate, and understand them. By the end of this lesson, you'll be well-equipped to work with strings in your C projects! š
In C programming, a string is an array of characters that ends with a null character (\0). Strings are used to store text data, such as names, sentences, and more.
char myString[10] = "Hello, World!";š Note: The size of the array must include space for the terminating null character (\0).
There are two main ways to create strings in C:
malloc().#include <stdio.h>
#include <stdlib.h>
int main() {
int length = 20;
char *myString = (char *)malloc(length * sizeof(char));
//... user input, string manipulation, etc.
// Don't forget to free the memory when you're done!
free(myString);
return 0;
}C provides various functions for manipulating strings, such as:
printf() - for printing stringsscanf() - for reading stringsstrlen() - for finding the length of a stringstrcpy() - for copying one string to anotherstrcmp() - for comparing two stringsstrcat() - for concatenating two stringsstrchr() - for finding a character in a stringLet's look at an example of using some of these functions:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char result[30];
// Concatenate str1 and str2
strcat(str1, " ");
strcat(str1, str2);
// Print the result
printf("%s\n", str1);
// Find the length of str1
int len = strlen(str1);
printf("The length of %s is %d\n", str1, len);
// Check if str1 is equal to "Hello World"
int result = strcmp(str1, "Hello World");
if (result == 0) {
printf("%s is equal to Hello World\n", str1);
}
return 0;
}What is a string in C programming?
How to create a string in C using an initializer?
What should you do when you're done with a dynamically allocated string using malloc()?