blogger Indonesia

Follow judhyns blog

Strings


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

  1. The size of the string is 6, which is the last element terminator, so you can use only 5 positions.

  2. In statement B, the string "Hello" is assigned so that the array elements are

    H  e  l  l  o  \0 
  3. The null terminator is appended automatically.

  4. Statement B puts the data in a string using standard array notation.

  5. You can print a string using the placeholder %s; the string is printed until it encounters a null character.

  6. The while loop in statement H inputs the string by reading character by character.

  7. The function getchar returns the character.

  8. Note that the counter is incremented up to 5 so as to accommodate the last null terminator.

  9. The null terminator is put in place by statement H.

  10. The while loop can be terminated before counter 5 by putting in the # character.

Points to Remember

  1. A string is a character array with a null terminator at the end.

  2. You can initialize the array using different methods.

No comments:

feed

PR Check

activesearchresults

judhyn's blog

 

http://www.judhyn.blogspot.com | |