C++ provides the following two types of string representations −

  • The C-style character string.
  • The string class type introduced with Standard C++.

 

C-style character string:

Strings are nothing but special kind of arrays in C++. A collection of homogeneous character elements is known as a string. 

Thus, we can say that string is a character array.

As in C, the string is a one – dimensional character array in C++ as well. The string is terminated with a null character which is represented as follows: ‘\0’. Thus, the length of any string is the number of characters + 1(the null character).

Example: 

char msg[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

Here, the character array msg, has a length of 6, which includes 5 characters and the 6 terminating null character.

The above example can be written as follows:

char msg[]= “Hello”;

Here, the C++ compiler automatically places the null character at the end of the string.

 

String class type:

The standard C++ library provides a String class type,that can be used to represent strings in C++ apart from the character array.

This can be illustrated with the help of an example as follows:

#include <iostream.h>

#include <string.h>

int main () {

 string str1 = "Hello";

 string str2 = "World";

 string str3;

 int  len ;


  // copy str1 into str3

   str3 = str1;

   cout << "str3 : " << str3 << endl;


   // joins str1 and str2

   str3 = str1 + str2;

   cout << "str1 + str2 : " << str3 << endl;


   // total length of str3 after joining

   len = str3.size();

   cout << "str3.size() :  " << len << endl;


   return 0;

}

The above code produces the following output.

Output:

str3 : Hello

str1 + str2 : HelloWorld

str3.size() :  10

We will learn more about the strings in the upcoming chapters.

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019