Tutorial Study Image

C++ strings


September 4, 2022, Learn eTutorial
1698

You will discover how to handle strings in C++ in this tutorial. You'll learn how to declare, initialize, as well as use them in a variety of input/output activities. Apart from that, we will also learn about what you mean by C++ string, the c-style character string in C++, and the main difference between C++ string as well as Character Array.

Object-oriented programming (OOPs) principles are used to some extent in the widely used general-purpose programming language C++. Through C++ strings, it enables you to operate with text and characters. All information regarding the String class is covered in this tutorial.

A string is nothing but a group/collection of characters. The C++ programming language typically uses two types of strings:

  • Objects of the string class  are strings
  • C-strings (C-style Strings) 
     

What exactly is a C++ String?

Text and character representation and manipulation are done using C++ strings. There are two distinct string representations available: the C-style character string and the String class which is mainly introduced in C++.

C++ strings

The C-Style Character String

A feature of the C programming language that is now available in C++ is the C-style character string. It resembles a character array that seems to be one dimension, holds a character sequence, and ends with a null character. So, if you want to maintain the word "Hello," you can create a C-style character string that contains the characters "H," "e," "l," "l," "o," and "0."

In this case, all you have to do is tell the compiler to save the word "Hello" as a string. But by default, it will still have the character "\0" at the end. Consider the following example, which demonstrates how to utilize the character array in order to build and store a C-style character string mainly in a variable.


#include 

using namespace std;

int main (){

   char greet[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   cout << "This is a wonderful greeting message for you: ";

   cout << greet << endl;

   return 0;

}

 

Output:


This is a wonderful greeting message for you: Hello

How to define a c-style string?


char str[] = "C++";
 

The string str in the above code contains 4 characters.

Even though "C++" has three characters, the null character \0 is automatically appended at the end of the given string. 

These are the different ways to define a string


char str[4] = "C++";
     
char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};
 

How C++ String Class is Introduced in C++?

OOPs concept is the foundation of C++, which allows you to express a string as an object of the String class (std:: string). The class allows you to rapidly declare a string variable and will also help to store any sequence of characters within it. Here is an illustration of how the String class can be used to represent a string.


#include <iostream>

using namespace std;

int main(){

    string greet = "Hello beautiful";

    cout << "This is a wonderful greeting message only for you: ";

    cout<<greet<<endl;

}

Output:


This is a wonderful greeting message only for you: Hello beautiful

The requirement to declare an array to hold characters is removed, as you can see in the output above.

What distinguishes a C++ string from a character array?

There are a few distinctions even though both the C-style character string and the C++ String class are used to represent strings.The most significant differences are:

  • While a string is a class that defines an object, a character array is an array.
  • The size of the character array is statically pre-allocated. As a result, more memory is not accessible during runtime, and unused Memory is wasted. The string size is not pre-allocated because of that there is no wastage and more memory is accessible during runtime.
  • Strings do not experience array decay, although character arrays do.
  • When it comes to implementation, strings take longer than character arrays.
  • More built-in functions to interact with and manipulate strings are available in the String class.

Input Functions in C++ String

A character or string can be added or removed from a string using the input functions. Input functions include,

  • getline(): Mainly used to read as well as to  store strings that users enter via input streams
  • push_back(): adds a new character to the string's conclusion.
  • pop_back(): pops out or deletes the last character from a string.

Example: let us write a program mainly using C++ input functions


#include<iostream>

#include<string>

using namespace std;

int main(){

// here declaring of a string variable is done

string s;

    cout << " Please enter a string: ";   

// Using getline() in order to accept input


getline(cin,s);

// For displaying the entered string

cout << "Our initial string will be : ";

cout << s << endl;

// just Insert a character i at the end of the string

//now we will be  using the push_back function

s.push_back('i');

// Displaying the string just after push_back

cout << "The new string is : ";

cout << s << endl;

// Deleting the i from the end using pop_back which we inserted

s.pop_back();

// Displaying the string after pop_back

cout << "After pop_back operation, our string will be : ";

cout << s << endl;

return 0;

}

Output:

Please enter a string: Welcome to learn eTutorials
Our initial string will be : Welcome to learn eTutorials
The new string is : Welcome to learn eTutorialsi
After pop_back operation, our string will be : Welcome to learn eTutorials

String Iterator Functions in C++

As suggested by the name, iterator functions are used to interact with iterators that traverse through each and every character in a string.

  • begin(): brings the iterator back to the beginning.
  • end():  it will return the iterator to the end
  • rbegin():  it will always return a reverse iterator that will be  pointing to the end   
  • rend():  it will always return a reverse iterator that will be  pointing to the start  

Example : let us write a program using string class iterator functions


#include<iostream>

#include<string>

using namespace std;

int main(){

string s = "LearneTutorials";

// Declaring the iterator

std::string::iterator iter;

// Declaring the iterator mainly for reverse functions

std::string::reverse_iterator iter1;

// Displaying the string

cout << " We are using the forward iterators : ";

for (iter=s.begin(); iter!=s.end(); iter++)

cout << *iter;

cout << endl;

// Displaying the reverse string

cout << "Now we are using the reverse iterators : ";

for (iter1=s.rbegin(); iter1!=s.rend(); iter1++)

cout << *iter1;

cout << endl;

return 0;

}

Output:

We are using the forward iterators : LearneTutorials
Now we are using the reverse iterators : slairotuTenraeL

To iterate through the string, in this case, we utilized the for loop in the code together with both forward and reverse iterators. Until it reached the end of the string, the first for loop, which employed a forward iterator, continued traversing and printing characters. We then used a reverse iterator in the second for loop, starting from the end and traversing and printing the characters all the way to the beginning of the string.

String Capacity functions in C++

Working with the size and capacity of the string is made easier by the C++ string capacity functions. The following are the main purposes of the capacity type:

  • capacity(): returns the amount of space that the compiler has allotted for a string.
  • resize(): This allows you to increase or decrease the length/size of the string.
  • length() :Returns the string's size.
  • shrink_to_fit(): Reduces and equalizes the capacity in order to preserve memory.

Example : now let us write a c++ program using string class capacity functions


#include<iostream>

#include<string>

using namespace std;

int main(){

string s = "C++ Programming is very much interesting!";

cout << "Initial string : ";

cout << s << endl;

// Resizing string using resize()

s.resize(15);

cout << "String after  resizing is done : ";

cout << s << endl;

// Using the capacity function

cout << "String's capacity is : ";

cout << s.capacity() << endl;

// Using the length function

cout<<"String's length will be : "<<s.length()<<endl;

// Using the shrink_to_fit function

s.shrink_to_fit();

cout << "Capacity of the post shrinking is : ";

cout << s.capacity() << endl;

return 0;

}

Output:

Initial string : C++ Programming is very much interesting!
String after  resizing is done : C++ Programming
String's capacity is : 41
String's length will be : 15
Capacity of the post shrinking is : 15

String manipulating functions in C++

With the use of operations like copying and swapping, you can manipulate a string using the manipulating functions.

  • copy (): It copies a portion of the char array's substring. The length of the copied substring and beginning position is specified by the parameters len and pos, respectively.
  • swap(): it will swap one string with another string.

Example: Now let us write a C++ program using string manipulating functions


#include<iostream>

#include<string>

using namespace std;

int main(){

string s1 = "Welcome All, let us enjoy  learning C++ with learn eTutorials";

string s2 = "C++ is Awesome!";

// Declaring character array

char ch_arr[80];

// Using copy() to copy elements from s1 and

// placing it in ch_arr

s1.copy(ch_arr,40,10);

// Printing of the array

cout << "Character array : ";

cout << ch_arr << endl << endl;

//  before swapping the strings

cout << " The String number 1 just before swapping is : ";

cout << s1 << endl;

cout << "The String number 2  just before swapping is : ";

cout << s2 << endl;

// using swap() function

s1.swap(s2);

// Strings after swapping

cout << "String number 1  after swapping will be : ";

cout << s1 << endl;

cout << "String number 2 after swapping will be : ";

cout << s2 << endl;

return 0;

}

Output:

Character array : l, let us enjoy  learning C++ with learn

The String number 1 just before swapping is : Welcome All, let us enjoy  learning C++ with learn eTutorials
The String number 2  just before swapping is : C++ is Awesome!
String number 1  after swapping will be : C++ is Awesome!
String number 2 after swapping will be : Welcome All, let us enjoy  learning C++ with learn eTutorials