Chapter 8
Strings

Defination : A string is a 1-D character array terminated by a null{ (‘\o’) this is null character}
Null character is used to denote string termination characters are stored in contiguous memory locations.
initialising Strings
since storing is an array of characters it can be initialised as follows.
char h[]={'H','Y','T','E','K'};
THERE IS ANOTHER SHORTCUT FOR INITIALIZING STRINGS
char h[]= "HYTEK"; in this case c adds null character automatically
Strings in memory
A string is stored just like an array in the memory as given below.

Pointers string
a string can be printed character by character using by printf & %c
But there is another convenient way to print strings in C
char hy[] = "HYTEK";
printf("%s",hy); prints the entire string
Taking string input from the user
we can use %s with scanf to take string input from the user
char hy[20];
scanf("%s",hy);
scanf automatically adds the null character when the enter key is pressed.
Notes
1. The string should be short enough to fit into the array
2. scanf cannot be used to input multi-word strings
gets() and puts()
gets() is a function which can be used to receive a multi-word string
char hy[30];
gets(hy); theentered string is stored in hy
Multiple gets()calls will be needed for multiple strings
likewise, puts can be used to output a string
puts(hy);
//prints the string places the cursor on the next line
Declaring a string using pointers we can declare strings using pointers
char *hyt="HYTEK";
This tells the compiler to store the string in memory and assigned address is stored in a char pointer
Notes
1. Once a string is defined using char hy[]=”HYTEK”; it cannot be initialised to something else.
2. A string defined using pointers can be reinitialized *hty = “HYTEK”;
Standard library functions for strings
C provides aset of standard library functions for string manipulation
Some of the most commonly used string functions are :
strlen()
this function is used to count the number of characters in the string executing the null ('\o') character
int length = strlen(hy);
these functions are declared under <string.h>
header file
strpy()
This function is used to copy the content of second string into first string passed to it
char source[]="HYTEK";
char target [30];
strcpy(target,source); target now contains "HYTEK"
Target string should have enough capacity to store the source string
strcat()
this function is used to concatenate two strings
char s1[11]="hello";
char s2[]="hytek";
strcat(s1,s2);
// s1 now contains"hellohytek"no space in between
strcmp()
This function is used to compare two strings it returns 0
if strings are equal negative value if first strings mismatching characters ASCII value is not greater than second strings corresponding missmatching character It returns positive values otherwise
strcmp("for","joke");//positive value
strcmp ("joke","for");//negative value