String Class in C++

Many people get confused with the definition of string in C++ whether it is a class or a data type. Let's make it clear that string is not a built-in data type but its behavior is very much similar to the fundamental data types.

String Class in C++

A String is a class from the standard template library that defines objects and is used to store a sequence of variable-length characters surrounded by double quotes(" ") that end with a null character '\0'. 

We use String data type to store words or a sentence kind of data.

  • Example 1: "Algolesson"
  • Example 2: "We are learning C++ Programming"

Note: All the functionality that we need to work with String class is available in the <string> header file so it is good practice to include this header file while working with String.


Some important properties of String:

  • In string, memory allocation takes place dynamically at runtime so no memory is wasted.
  • String implementations are slower than character arrays.
  • String provides several inbuilt functionalities that we can use to perform operations on strings.


How do you Declare and Initialize a string in C++?

String declaration is very much like any other data type, we use the string keyword followed by string name (variable name) which is going to store our value. In the below example, str is the string name and the default initialization of this string is empty. 

ex: string str; //str is an empty string


There are multiple ways to initialize a string in C++ and below are a few examples:

String Initialization Examples Definition
string str; In this example, the string is empty which is a default Initialization whenever we create a string.
string str2(str1); In this example, we are copying the value of one string (str1) into another string (str2).
string str("algolesson"); In this example, the str string is copying the value of the string literal present in double quotes "algolesson".
string str = "algolesson"; In this example also, the str string is copying the value of the string literal present in double quotes "algolesson".
string str(n, 'e'); In this example also, we initialize the string with n copies of the character 'e'.

C++ Code for string declaration and Initialization.

//C++ Code example for initialization
#include<iostream>
#include<string>
using namespace std;

int main(){

    string str1; //empty string
    string str2 ("What is your name?");
    string answer = "My name is John";
    str1 = "I am a Software Engineer.";
    string copyChar (3, 'w');
    string companyName (".algolesson.com");

    //Printing the string values
    cout<<str2<<endl;
    cout<<answer<<" "<<str1<<endl;
    cout<<copyChar<<companyName<<endl;

    return 0;
}
Output:
What is your name?
My name is John I am a Software Engineer.
www.algolesson.com

There are several operations that you can perform on String in C++ programming language. Let's understand each of them one by one. 

Read and Write Operations on String in C++ (getline()).

There are multiple ways to perform read/write operations on a string one is by using cin (character input) and cout (character output) objects but there is one limitation the cin can read only one word and everything after the white space is discarded. Let's understand with one example:
//C++ code to read and write string
#include<iostream>
#include<string>
using namespace std;

int main(){
    //empty string
    string str;
    //input from the user
    cout<<"Enter a string: ";
    cin>>str;
    cout<<str<<endl;

    return 0;
}
Output:
Enter a string: Hello World
Hello

If you observe in the above example, we entered a two-word string "Hello World" separated by white space but our string variable str is able to only the first word. To overcome this problem and to read an entire line of string we use the getline() standard library function which read the input one line at a time until the EOF(End of File) is encountered. 

Let's understand getline()in C++ with one example:
//C++ code to read and write string using getline()
#include<iostream>
#include<string>
using namespace std;

int main(){
    //empty string
    string name, subject;

    cout<<"What is your name? ";
    //use of getline() function
    getline(cin,name); 
    cout<<name<<endl;

    cout<<"Enter your subject name: ";
    //use of getline() function with delimiting character
    getline(cin,subject,'-'); 
    cout<<subject;
    
    return 0;
}
Output:
What is your name? I am John Wick
I am John Wick
Enter your subject name: Operating-System
Operating
In the above example code, we have taken user input using the getline() function, and when we use it for the first time (getline(cin, name)) we can observe that the entire line is displayed which means that getline() function capture characters even after white spaces. 

When we use the getline() function for the second time (getline(cin, subject, '-')) we have added a delimiting character (-) that is added as the third parameter of the function and it means that any character that appears after this delimiting character is discarded.

How to Access String Elements in C++?

String class is used to store a sequence of characters and each character takes one byte of memory. There are several ways to access individual characters of a string. 
String Function Definition
operator [pos] This function is used to return a reference of the character at position pos in the string. We can also modify the character of that position (pos).
at() This function is used to return a reference of the character at position pos in the string. We can also modify the character of that position.
back() This function is used to return a reference of the last character of the string. We can also add one character at the end using this function.
front() This function is used to return a reference of the first character of the string. We can also add one character at the front using this function.

Let's understand the ways of accessing characters in a string in C++ code:
/*C++ program to access string elements*/
#include<iostream>
#include<string>
using namespace std;

int main(){

  string str = "Welcome to Algolesson";
  //working of [] operator
  for(int i = 0; i < str.size(); i++){
    cout<<str[i];
  }
  //working of at()
  cout<<endl;
  for(int i = 0; i < str.size(); i++){
    cout<<str.at(i);
  }
  cout<<endl;
  //working of back()
  str.back() = '!';
  cout<<"The last character of the string is: "<<str.back()<<endl;
  //working of front()
  str.front() = '@';
  cout<<"The first  character of the string is: "<<str.front()<<endl;

  cout<<"String after operation: "<<str<<endl;
  return 0;
}
Output:
Welcome to Algolesson
Welcome to Algolesson
The last character of the string is: !
The first  character of the string is: @
String after operation: @elcome to Algolesso!



I hope you found this post useful, please write a comment if you found anything incorrect or share your valuable feedback. 

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS