What is a String in C++?

A string is a sequence of characters in C++. In other programming languages, a string is often represented as an array of characters.

However, in C++, the standard library provides a string class that can be used to represent a string.

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

Also Read: What is a Preprocessor in C/C++?

Declaring a string

Strings can be declared using the string data type and initialised with a sequence of characters enclosed in double quotes. They can also be concatenated, compared, and modified using various functions and operators provided by the string class.

In C++, you can declare a string using the string keyword. For example, the following code declares a string variable:

#include <string>
using namespace std;

int main()
{
    string myString = "Hello, World!";
    return 0;
}

In this example, we first include the <string> header file, which provides the string class. We then declare a string variable called myString and initialize it with the string “Hello, World!”.

Accessing a string

To access a string in C++, you can use the array subscript operator []. For example, the following code accesses the first character of the string myString:

#include <string>
using namespace std;

int main()
{
    string myString = "Hello, World!";
    char firstChar = myString[0];
    return 0;
}

In this example, we use the array subscript operator to access the first character of the string myString and assign it to the variable firstChar.

Modifying a string

In C++, you can modify a string using various string member functions. For example, the following code modifies the string myString by replacing the substring “World” with “Universe”:

#include <string>
using namespace std;

int main()
{
    string myString = "Hello, World!";
    myString.replace(7, 5, "Universe");
    return 0;
}

In this example, we use the replace() member function to replace the substring “World” in the string myString with “Universe”. The first argument to the replace() the function is the position at which to start the replacement, and the second argument is the length of the substring to replace. The third argument is the new substring to insert.

Leave a Reply