Strings in C:
String: In C, a string is a sequence of characters. A string is terminated by the null character called null( \0 ) [null means nothing, it holds zero]. The null(termination) character is important in a string it is the only way to identify where the string ends. When you define a string, you must reserve a space for the null(\0) character.
For example, to declare a string with the size that holds n characters, the size of the array must be at least n+1. This is because the last index is implicitly initialized with the null in memory.
There are two ways to declare a string in C:
1. By character array
2. By string literal
By character array: Strings are actually a one-dimensional array of characters terminated by the null character '\0'.
Declaring string by character array in C:
char str[10] = {'L','e','a','r','n','c','o','d','e'};
The size of the character array must be the (length of the string)+1.
when declaration and initialization are done simultaneously, size is not mandatory. so we can write the above code as
char str[] = {'L','e','a','r','n','c','o','d','e'};
By string literal: The array initialization takes place in a string literal. Actually, you don't need to place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string literal.
Declaring string by using the string literal in C:
char str[ ] = "Learncode";
The compiler automatically creates an array of 10 characters that is sufficient enough to hold the Learncode text and \0.
Example1: C program to declare and print a string without for loop.
Program
Output:
Explanation: The '%s' is used as a format specifier for input and output of string in C language. More about Format specifiers.
Example2: C program to print the string using for loop.
Program:
Output:
Explanation: The '%c' is used as a format specifier for printing each character in the string. Variable i is used as indexing in the string.
Example3: C program to take a string as input and print the string.
Program:
No comments:
Post a Comment