What is a String in C++

String in C++

Often time you may come across a situation where you want to store characters and perform some operations on it.

C programming provides you with a facility of char array. But it becomes difficult when dealing with large operations and also maintaining the char array. In C++, you are provided with String Class, which have been predefined in C++ header files.

string in c++

In this post, we will learn about the various features of Strings and their practical uses for easy programming.

what is a string in c++

At the beginner level, remember that Strings are based on char array, but it is optimized to achieve memory management, null termination and allocation in the string header class, which is very easy to use. A String class is a container class similar to other containers like vector, set, and maps. We iterate by using a simple [] operator like an array. The length of the string is dynamic; that is, it can be changed at the run-time.

Some of the important functions in C++ are :

#include<bits/stdc++.h>
using namespace std;
 
int main(){
//A string variable can be initialized in following ways:
  
  string str1("first string"); 
  // output:  first string

   // initialization by character 
    string str3(5, '#');
  // output:  #####

    // initialization with another string 
    string str2(str1); 
  
  // initialization by part of another string
    string str5(str2.begin(), str2.begin() + 5); 

    // initialization by part of another string 
    string str4(str1, 6, 6); //    from 6th index (second parameter) 
                             // 6 characters (third parameter) 
  
str.clear(); //Clear:  The clear function empty the string variable. 

Length(); The str.length()  //returns the size of char array.

str.at(); //  The str.at() returns the character position at that index

str.append(); //  The str.append() adds a string with argument passed through it.

str.find();  //  The str.find() is used to check whether a particular part of string is present or not.

substr(); //It is used to fetch a sub-string from the main string.

str.erase(); // It is used to delete the characters from the given index value.

str.replace(); // It is used to replace a part of string with other.
return 0;
}

All of the above basic options help perform basic operations and even in competitive programming on a string.

Show More

Leave a Reply

Back to top button