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:
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:
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:
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:
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:
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.
xxxxxxxxxx
int main() {
std::string message = "Hello, AlgoDaily!";
// Length of the string
int length = message.length();
std::cout << "Length: " << length << std::endl;
// Accessing individual characters
char firstChar = message[0];
std::cout << "First character: " << firstChar << std::endl;
// Substring
std::string substring = message.substr(7);
std::cout << "Substring: " << substring << std::endl;
// Concatenation
std::string name = "Alice";
std::string greeting = "Hello, " + name;
std::cout << greeting << std::endl;
return 0;
}