In this lesson, you will learn about strings in C, their usage, and examples to better understand the topic.
The string data type is a sequence of characters that can contain letters or any alphabets or numbers. During declaration strings are enclosed within double or single quotes; however, they are not treated in the same manner while printing. To clarify this explanation, let’s see the example below.
char s[] = "Welcome to Learnmodo";
char s[] = "Learmodo.com";
char s[200] = "Learmodo.com";
char s[] = { 'l', 'e', 'a', 'r', 'n', 'm', 'o', 'd', 'o', 'char s[] = "Welcome to Learnmodo";
char s[] = "Learmodo.com";
char s[200] = "Learmodo.com";
char s[] = { 'l', 'e', 'a', 'r', 'n', 'm', 'o', 'd', 'o', '\0' };
' };
Note
The string data type in C is different than in other languages; you must use the char type to create a string and terminate by null character\0.
Example of String in C using scanf Function
//Example of program reads the input from user
#include <stdio.h>
int main ()
{
char sub[50]; //declare the sub array of size 50
printf ("Please enter the subject name: ");
scanf ("%s", sub); // takes the string input from user
printf ("Subject you selected is %s.", sub); // display the subject name
return 0;
}
Output
Please enter the subject name: Programming
Subject you selected is Programming.
Example of String in C using fgets() function
Below program reads the user input using fgets() function in one line and uses the puts() function to display it.
//Example of program reads the input from user in one line
#include <stdio.h>
int main ()
{
char sub[50]; //declare the sub array of size 50
printf ("Please enter the subject name: ");
fgets (sub, sizeof (sub), stdin);
puts (sub); // display the subject
return 0;
}
Output
Please enter the subject name: Programming
Programming
In the next lesson, you will learn about built-in string functions in C.