Google News
logo
Strings In C Language
String is a collection of characters positioned sequentially one after the other, used to represent names of items, persons, cities, countries and etc. To handle strings there is no direct datatype in c, instead we have to access them as a normal array of characters. Which is terminated by a null character ‘\0’, thus a null-terminated string contains the characters that comprise the string followed by a null. This null character indicates the end of the string.

Strings are always enclosed by double quotes, whereas, character is enclosed by single quotes in C.

If we declare char arr[20]; means ‘arr’ is an array name with the maximum capacity of 20 characters, it can hold a string with a maximum length of 19 characters and 1 byte for null character.
  Example for C string :
char string[20] = { ‘w’ , ’e’ , ‘l’ , ‘c’ , ‘o’ , ‘m’ , ‘e’ ,’-’ , ‘t’ , ‘o’ ,’-’,  ’f’ , ‘t’ , ‘l’ ,’ ’, ‘\0’}; (or)
char string[20] = “welcome-to-ftl”; (or)
char string []    = “welcome-to-ftl”;

Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of memory space is allocated for holding the string value.

When we declare char as “string[]”, memory space will be allocated as per the requirement during execution of the program.

char a[5]=”ftl”;	//compiler raises an error because the size of array is not enough for string
char a[20]=”hello”; 	//remaining 14 locations automatically filled with null characters

Accessing individual character in a string is just as accessing elements in the array. The index of the character should be specified as array subscript.

  For example :
char c[]=”ftl”;
The expression    ‘c[0]’ accesses the first character ‘f’
		          ‘c[1]’ accesses the third character ‘t’,……….
                   Similarly remaining elements are accessed.