Character Array/ String
It is a sequence of characters terminated by a special symbol ‘\n’
Declaration | char str[8];
Initialization |
option 1( static)- char str[9]= {‘e’, ‘l’, ‘e’ , ‘p’, ‘h’, ‘a’, ‘n’ ,
‘t’,‘\0’ };
-char str[]= {‘t’, ‘r’, ‘e’, ‘e’, ‘\0’,};
option 2(static)- char str[9]= “elephant”;
char str[]= “elephant”;
option 3(Dynamic)- char w[100];
printf(“ \n Enter a string:\n”);
gets(w);
OR
Scanf(“%s”, w)
Accessing
Some string manipulation functions contained in the library “string.h”
1) Strcmp – used for compairing strings
2) Strcpy- used for copying strings
3) Strlen- used for obtaining lengths of strings
4) Strcat- used for concatenating(joining) 2 strings
Int strlen ( string )
Example :
char w[100];
w[0]= ‘a’;
w[1]= ‘t’;
w[2]= ‘\0’;
printf(“%d”, strlen(w));
ex: str1= “bomb” str2=”cat”
strcmp(“bomb”, “cat”); = -1
str1=”cat” str2=”bomb”
strcmo(“cat”, “bomb”); = 1
str1=”bomb” str2=”bomd”
strcmp(“bomb”, “bomd”); = -1
str1=”bomb” str2=”bom” = 1
str1=”b” str2=”B” =1