STRINGS AS AN ARRAY OF CHARACTERS
Introduction
A string is defined as an array of characters. Strings are terminated by the special character ‘\o’; this is called a null parameter or null terminator. When you declare the string, you should ensure that you should have sufficient room for the null terminator. The null terminator has ASCII value 0.
Program
main ( ) { char s1[6]; \\ A char s2[6]; char ch; int cnt = 0; s1 = "Hello"; \\ B printf ("%s \n", s1); \\ C s2 = {'H', 'e', 'l', 'l', 'o'} \\ D printf("%s \n", s2); \\ E while ( (ch = getchar() )! = '#' && (cnt < 6-1) ) \\ F s1[cnt++] = ch; \\ G s1[cnt] = '\0'; \\ H }
Explanation
-
The size of the string is 6, which is the last element terminator, so you can use only 5 positions.
-
In statement B, the string "Hello" is assigned so that the array elements are
H e l l o \0
-
The null terminator is appended automatically.
-
Statement B puts the data in a string using standard array notation.
-
You can print a string using the placeholder %s; the string is printed until it encounters a null character.
-
The while loop in statement H inputs the string by reading character by character.
-
The function getchar returns the character.
-
Note that the counter is incremented up to 5 so as to accommodate the last null terminator.
-
The null terminator is put in place by statement H.
-
The while loop can be terminated before counter 5 by putting in the # character.
Points to Remember
-
A string is a character array with a null terminator at the end.
-
You can initialize the array using different methods.
No comments:
Post a Comment