- char c[] = "abcd";
- char c[50] = "abcd";
- char c[] = {'a', 'b', 'c', 'd', '\0'};
- char c[5] = {'a', 'b', 'c', 'd', '\0'};
How to read a line of text?
You can use the fgets() function to read a line of string. And, you can use puts() to display the string.
Example:-
#include <stdio.h>
int main()
{char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output:-
Enter name: C language
Name: C language
strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (the unsigned integer type).#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
printf("Length of string a = %zu \n",strlen(a));
// using the %zu format specifier to print size_t
printf("Length of string b = %zu \n",strlen(b));
return 0;
}
Output:-
Length of string a = 7
Length of string b = 7
2).strcpy():- The strcpy() function copies the string pointed by source (including the null character) to the destination.
The strcpy() function also returns the copied string.
The strcpy() function is defined in the string.h header file.
syntax:-
char* strcpy(char* destination, const char* source);
Example:-
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "C programming";
char str2[20];
strcpy(str2, str1); // copying str1 to str2
puts(str2); // C programming
return 0;
}
Output:- C programming
3). strcmp():- The strcmp() compares two strings character by character.If the first character of two strings is equal, the next character of two strings are compared. This continues until the corresponding characters of two strings are different or a null character '\0' is reached.
It is defined in the string.h header file.
Return Value from strcmp():-
return 0:- if both strings are identical (equal).
return negative integer:- if the ASCII value of the first unmatched character is less than the second.
return positive integer:-if the ASCII value of the first unmatched character is greater than the second.
strcat() function concatenates the destination string and the source string, and the result is stored in the destination string.
0 Comments