Mark As Completed Discussion

Working with Strings

In C++, strings are a fundamental data type that allows you to work with text. The std::string class from the C++ Standard Library provides a rich set of functions and operators for string manipulation.

To use strings in C++, you need to include the <string> header file:

TEXT/X-C++SRC
1#include <string>

Let's explore some common operations you can perform on strings:

Length of the String

You can get the length of a string using the length() function. For example:

TEXT/X-C++SRC
1std::string message = "Hello, AlgoDaily!";
2int length = message.length();

The length variable will contain the number of characters in the string.

Accessing Individual Characters

You can access individual characters of a string using the [] operator. For example:

TEXT/X-C++SRC
1std::string message = "Hello, AlgoDaily!";
2char firstChar = message[0];

The firstChar variable will contain the first character of the string.

Substring

You can extract a substring from a string using the substr() function. This function takes two parameters: the starting index and the length of the substring. For example:

TEXT/X-C++SRC
1std::string message = "Hello, AlgoDaily!";
2std::string substring = message.substr(7);

The substring variable will contain the substring starting from index 7 till the end of the string.

Concatenation

You can concatenate strings using the + operator. For example:

TEXT/X-C++SRC
1std::string name = "Alice";
2std::string greeting = "Hello, " + name;

The greeting variable will contain the concatenated string.

These are just a few of the many string operations available in C++. Using these operations, you can manipulate and process text efficiently.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment