Group of characters can be stored in a character array. String in C language is an array of characters that is terminated by \0 (null character)
Declaration :
There are two ways to declare string in c language.
- By char array
- By string literal
string by char array
Syntax :
char ch[]={'h','e','l','l','o','\0'};
Note :
- Declaring string size is not mandatory.
string by string literal
Syntax :
char ch[]="hello";
Note :
-
- ‘\0’ is not necessary. C inserts the null character automatically.
Important Points :
- The ‘%s’ is used to print string in c language.
Example of string :
#include <stdio.h> int main(void) { char ch[11] = {'h', 'e', 'l', 'l', 'o', '\0'}; char ch2[11] = "hello"; char c = 'h'; printf("Character value is : %c\n",c); printf("\nChar Array Value is : %s\n", ch); printf("\nString Literal Value is : %s\n", ch2); return 0; }
Output :
Character value is : h Char Array Value is : hello String Literal Value is : hello
Example of gets and puts function :
#include <stdio.h> int main(void) { char name[25] ; printf ( "Enter name : " ) ; gets ( name ) ;//for input printf("\nYour Name is : "); puts ( name ) ;//for output return 0; }
Output :
Enter name : hello Your Name is : hello
String functions
Sr.No. | Function & Purpose |
---|---|
1 | strcpy(s1, s2);
Copies string s2 into string s1. |
2 | strcat(s1, s2);
Concatenates string s2 onto the end of string s1. |
3 | strlen(s1);
Returns the length of string s1. |
4 | strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. |
5 | strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1. |
6 | strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1. |