C Programming and Data Structures (41 Blogs)

Everything you Need to know About Strings in C++

Published on Aug 07,2019 39 Views


myMock Interview Service for Real Tech Jobs


myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

The term string means an ordered sequence of characters. A sequence of characters can be represented using an object of a class in C++.  The class which provides a definition to do so is called a String class. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. In C++ the enclosing delimiters are double-quotes. In this “Strings in C++” article I’ll be discussing the following topics:


String Class and Character Array Difference

String classCharacter Array
String class is a class which defines objects that can be represented as a stream of charactersCharacter array is simply an array of characters.
In the case of strings, memory is allocated dynamically thus more memory can be allocated at run time on demandSize of the character array has to be allocated statically thus more memory cannot be allocated at run time if required
String class defines a number of functionalities which allow manifold operations on strings.Character array do not offer many in-built functions to manipulate strings
Strings are slower when compared to implementation than the character array.Implementation of a character array is faster.


Declare and Initialize a Strings in C++

strings-in-c++Initialization of string in C++ is pretty simple!. We can use any one of the following methods.

using namespace std;
string std_string;


std::string std_string;
#include <iostream>

using namespace std;
int main () {

   char ch[12] = {'H', 'e', 'l', 'l', 'o', ' ', 'b', 'y',' ', 'c', 'h', ''};

   string st = "Hello by st";
   std::string std_st = "Hello by std_st";

   cout << ch << endl;
   cout << st << endl;
   cout << std_st << endl;

   return 0;


Hello by ch
Hello by st
Hello by std_st

In this example, we have shown both the character array (ch) and the string class (st and std_st) initialization methods. First, we used the character array method by defining a character array ch[12] which contains 12 elements and terminates with a null character. In the second part, we used a string class method.


Operations on Strings in C++

The advantage of using string class is that there are several built-in functions in C++ to manipulate them. This makes programming easy and effective. Let us take up certain important string manipulation functions and understand them by looking at some examples.

String Size: Both size() and length() methods can be used to return the size of the object.

cout << st.length() <<endl;
cout << st.size() <<endl;




String Concatenation: We can concatenate two or more strings simply by using + operator between them

string new_string = st + " and " + std_st;
cout << new_string <<endl;


Hello by st and Hello by std_st


Appending Strings: The .append(string) class member function can be used to concatenate and append a string at a specific character location in the string. If a programmer puts str.append(str1, p, n), then it means that n number of characters from position p in string str1 will be appended to the end of the str.

string str = "I enjoy learning ";
string str1 = "Python, C++, or C";

str.append(str1, 8, 3);
cout << str << endl;


I enjoy learning C++


Searching strings: We can use the find() member function to find the first occurrence of a string inside another. find() will look for string needle inside string haystack starting from position pos and return the position of the first occurrence of the needle. The function rfind() works similarly, except it returns the last occurrence of the passed string.

string haystack = "Hello World!";
string needle = "o";
cout << haystack.find(needle)<<endl;
cout << haystack.find(needle, 4)<<endl;
cout << haystack.find(needle, 5)<<endl;
cout << haystack.find(needle, 8)<<endl;



The first cout command will simply print “4” which is the index of the first occurrence of “o” in the haystack string. If we want the “o” in “World”, we need to modify “pos” to point past the first occurrence. haystack.find(needle, 4) would again return 4, while haystack.find(needle, 5) would give 7. If the substring isn’t found, find() returns std::string::npos.

Npos is a special value equal to the maximum value representable by the type size_type. Here it is 4294967295. Generally, it is used either as the end of string indicator by the functions that expect a string index or as the error indicator by the functions that return a string index.


This simple code searches a string for all occurrences of “C++” in str2 and prints their positions:

string str2= "C++ is an object-oriented programming language and includes classes, inheritance, polymorphism, data abstraction and encapsulation.C++ allows exception handling, and function overloading which are not possible in C.C++ is a powerful, efficient and fast language.";

for(string::size_type i = 0, tfind; (tfind = wikistr.find("C++", i)) != string::npos; i = tfind + 1)
 std::cout << "Found occurrence of 'C++' at position " << tfind << std::endl;


Found occurrence of 'C++' at position 0
Found occurrence of 'C++' at position 132
Found occurrence of 'C++' at position 217


using namespace std; 
class base 
    void fun_1() { cout << "base class function 1n"; } 
    virtual void fun_2() { cout << "base class function 2n"; } 
    virtual void fun_3() { cout << "base class function 3n"; } 
    virtual void fun_4() { cout << "base class function 4n"; } 
class derived : public base 
    void fun_1() { cout << "derived class function 1n"; } 
    void fun_2() { cout << "derived class function 2n"; } 
    void fun_4(int x) { cout << "derived class function 4n"; } }; int main() { base *ptr; derived obj1; ptr = &obj1; // Early binding because fun1() is non-virtual // in base ptr->fun_1(); 
    // Late binding (RTP) 
    // Late binding (RTP) 
    // Late binding (RTP) 
    // Early binding but this function call is 
    // illegal(produces error) because pointer 
    // is of base type and function is of 
    // derived class 


base class function 1
derived class function 2
base class function 3
base class function 4


With this, we come to an end to this article on Strings in C++. I hope you got an understanding of the various Operations that can be performed on it. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course are designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.


Browse Categories

webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.