String
In C programming language, a string is a group of characters that are stored in a character array. Strings are used to represent text or any other sequence of characters. Each string is terminated with a null character '\0', which tells the program where the string ends.
Let's explore some examples of how to store and manipulate strings in C
Example 1
copy
#include<stdio.h>
int main(){
char word[] = {'h','e','l','l','o','\0'};
printf("%s",word);
return 0;
}
Output
hello
In this example, we declare a character array named "word" and initialize it with the characters 'h', 'e', 'l', 'l', 'o', and the null character '\0'. We then use the printf() function to print the contents of the "word" array as a string.
Example 2
copy
#include<stdio.h>
int main(){
char word[6] = "hello";
printf("%s",word);
return 0;
}
Output
hello
In this example, we declare a character array named "word" with a size of 6 and initialize it with the string "hello". The null character '\0' is automatically added by the compiler.
Example 3
copy
#include<stdio.h>
int main(){
char sentance[][15] = {"hi I am aman","this is a boy","he is a girl"};
for (int i = 0; i < 3; i++)
{
printf("%s\n",sentance[i]);
}
return 0;
}
Output
copy
hi I am aman
this is a boy
he is a girl
In this example, we declare a two-dimensional character array named "sentance". The first dimension specifies the number of strings, and the second dimension specifies the length of each string. We initialize the "sentance" array with three strings, and then use a for loop to print each string on a new line.
Example 4
copy
#include <stdio.h>
#include <string.h>
int main()
{
char word1[] = "hi i am aman";
char word2[15];
strcpy(word1, "he is a boy");
strcpy(word2, word1);
printf("%s \n%s\n",word1,word2);
return 0;
}
Output
copy
he is a boy
he is a boy
In this example, we declare two character arrays named "word1" and "word2". We use the strcpy() function to copy the string "he is a boy" to the "word1" array, and then copy the contents of "word1" to "word2". We then use printf() to print the contents of both arrays.