天道酬勤,学无止境

Computer Programming - Strings



During our discussion about characters, we learnt that character data type deals with a single character and you can assign any character from your keyboard to a character type variable.

Now, let's move a little bit ahead and consider a situation where we need to store more than one character in a variable. We have seen that C programming does not allow to store more than one character in a character type variable. So the following statements are invalid in C programming and produce syntax errors −

char ch1 = 'ab';
char ch2 = '10';

We have also seen how to use the concept of arrays to store more than one value of similar data type in a variable. Here is the syntax to store and print five numbers in an array of int type −

#include <stdio.h>

main() {
   int number[5] = {10, 20, 30, 40, 50};
   int i = 0;
        
   while( i < 5 ) {
      printf("number[%d] = %dn", i, number[i] );
      i = i + 1;
   }
}

When the above code is compiled and executed, it produces the following result −

number[0] = 10
number[1] = 20
number[2] = 30
number[3] = 40
number[4] = 50

Now, let's define an array of five characters in the same way as we did for numbers and try to print them −

#include <stdio.h>

main() {
   char ch[5] = {'H', 'e', 'l', 'l', 'o'};
   int i = 0;
        
   while( i < 5 ) {
      printf("ch[%d] = %cn", i, ch[i] );
      i = i + 1;
   }
}

Here, we used %c to print character value. When the above code is compiled and executed, it produces the following result −

ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o

If you are done with the above example, then I think you understood how strings work in C programming, because strings in C are represented as arrays of characters. C programming simplified the assignment and printing of strings. Let's check the same example once again with a simplified syntax −

#include <stdio.h>

main() {
   char ch[5] = "Hello";
   int i = 0;
    
   /* Print as a complete string */
   printf("String = %sn", ch);  

   /* Print character by character */
   while( i < 5 ) {
      printf("ch[%d] = %cn", i, ch[i] );
      i = i + 1;
   }
}

Here, we used %s to print the full string value using array name ch, which is actually the beginning of the memory address holding ch variable as shown below −

String Presentation in C/C++

Although it's not visible from the above examples, a C program internally assigns null character '