Understanding String Handling In C++

String  is the collection of characters. In C++ string variables are character array and literals are declared within the double quotes same as "C"  language but C++ string is much better then C's string. Let's understand with some examples. 

String Literals :

#include <iostream>

using namespace std;

int main(void) {

char str1[20] = "Hello";

//Space allowed
char str2[20]  =  "Hello World";

//Special character allowed
char str3[20]  =  "Hello,@#!$%^& World";

//Allow string to be continue in next line
char str4 [20]  =  "Hello \

//Valid literal, all words are in one line
char str5[20] = "Hello" "My" "world";

//All words are in one line with , and space
char str6[20] ="Hello, " "my " "world";



return 0;


Output : -


Hello World

Hello,@#!$%^& World

Hello  World


Hello, my world

String Variable :

#include <iostream>

using namespace std;

int main(void) {

string str1,str2;

cout<<"Enter 1st string - ";

/*1st way to take input from user, 
it will accept string along with whitespace*/


cout<<"Enter 2nd string - ";

/*another way to take input from user,
 it does not accept space. */


cout<<"Strings are -"<<str1<<endl<<str2;

return 0;


Output :

Enter 1st string - Hello World

Enter 2nd string - Hello World

Strings are -Hello World

Explanation 1 : 

1 - String class allows user to use dynamic string without defining the size of characters.

 In C we have to define size of the array. 

2 - cin behaves same as scanf method in c, it does not accept multiple word string. In C we used gets method and in C++ string class provides getline method, it accepts multi word string. 

Operator Overloading With String :

Operator overloading is the part of polymorphism where one operator can work in different ways, usually =,+,>,== operators works with numeric values, C++ allows these operators to work with string as well. Many of the string method's functionalities are done by operators.  

#include <iostream>

Note in this example std is defined

recommended: define std to avoid extra writing std::

int main() {

std::string str1 ,str2;

std::string copyStr,catStr;

std::cout<<"Enetr 1st string";


/* Creating copy of string using assignment operator */ 

copyStr = str1;

std::cout<<"The copy of str1 is = "<<copyStr<<std::endl;

std::cout<<"Enter 2nd string";


/* Concate or adding two string using + operator */

catStr = str1+str2;

std::cout<<"The concatenation of strings ="<<catStr<<std::endl;

/* Comparing strings using == operator*/

if(str1 == str2 ) {

  std::cout<<"Strings are same"<<std::endl;


else {

  std::cout<<"Strings are different"<<std::endl;


/* Comparing string size using > and < operators */

if(str1 > str2) {

  std::cout<<"str1 is bigger than str2"<<std::endl;


else {

  std::cout<<"str2 is bigger than str1"<<std::endl;



Thanks for reading, please do share and comment your suggestions.

No comments

Powered by Blogger.