lab-11-strings - ICS 103 Computer Programming in C Lab#12 Strings Objective Practice how to use Strings String Declaration Initialization A string is a

lab-11-strings - ICS 103 Computer Programming in C Lab#12...

This preview shows page 1 - 2 out of 4 pages.

ICS 103 – Computer Programming in C Lab #12: Strings Objective: Practice how to use Strings. String Declaration & Initialization A string is a list of characters enclosed in double quotes. It is represented in C as an array of characters However, one additional cell is required for storing the terminating character, ’\0’ ,called NULL Example: Even though the string ”I like C” has 8 characters, we need to declare an array of size 9. char str[9]=”I like C”; ’I’ ’ ’ ’l’ ’i’ ’k’ ’e’ ’ ’ ’C’ ’\0’ Note that in the example above, the null character is automatically inserted by the compiler All the string functions in C require the presence of the NULL character to work correctly. Strings can also be declared without specifying the size as in: char str[]=”I like C”; In this case, sufficient storage is allocated including that for NULL Like array, the individual characters of a string can be accessed by specifying the index. Example, assuming the above assignment, str[4] is the character ‘k’ Consider the following example where the program reads the characters of the string character by character. The last character read is ‘\n’ (Enter key). Once outside the loop we assign the NULL character ‘\0’ at the location of ‘\n’ to make the sequence of characters a string. Now run the example and see what happens when you comment or uncomment the statement assigning the ‘\0’ character. #include <stdio.h>
Image of page 1
Image of page 2

You've reached the end of your free preview.

Want to read all 4 pages?

  • Fall '14
  • ASCII, null character

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture