C++ Strings: String Operation with examples

5 / 100

C++ Strings are a data type used to store and manipulate sequences of characters. They are an important part of the C++ standard template library (STL) and are widely used in C++ programming.

In C++, strings are objects of the std::string class. This class provides a variety of methods for working with strings, including operations such as concatenation, comparison, and search.

One way to create a string is to initialize it with a string literal. For example:

std::string myString = "Hello, World!";



You can also use the std::string constructor to create a string from a character array or a single character. For example:


char myCharArray[] = {'H', 'e', 'l', 'l', 'o'};
std::string myString(myCharArray);
std::string myString2(1, 'a');



You can also use the assignment operator (=) to assign a new value to a string. For example:


std::string myString;
myString = "Hello, World!";



The std::string class provides a variety of methods for working with strings. Some of the most commonly used methods include:

  • length() : returns the number of characters in the string.
  • size() : returns the number of characters in the string.
  • empty() : returns true if the string is empty.
  • append() : adds one or more characters to the end of the string.
  • push_back() : adds a single character to the end of the string.
  • insert() : inserts one or more characters into the string at a specified position.
  • erase() : deletes one or more characters from the string.
  • replace() : replaces one or more characters in the string with new characters.
  • find() : searches for a specified substring within the string and returns its position.
  • substr() : returns a substring from the original string
  • compare() : compare the contents of two string
  • Here is an example which shows some of these functions in action:
#include<bits/stdc++.h>
int main()
{
std::string myString = "Hello, World!";
std::cout << "The length of myString is: " << myString.length() << std::endl;
myString.push_back('!');
std::cout << "After push_back myString is: " << myString << std::endl;
myString.erase(7, 7);
std::cout << "After erase myString is: " << myString << std::endl
myString.insert(7, "World ");
std::cout << "After insert myString is: " << myString << std::endl;
std::cout << "The substring of myString is: " << myString.substr(7,5) << std::endl;
return 0;
}

It is also possible to use the + operator to concatenate two strings or a string and a character array or a character. For example:

std::string myString1 = "Hello, ";
std::string myString2 = "world";
std::string myString3= myString1+ myString2;

Leave a Comment