Strings
Lesson 8Author : Afrixi
Last Updated : November, 2022
Strings in C++
In C++, strings are used to represent a sequence of characters. They are useful for storing and manipulating text data, such as names, addresses, and messages. Strings in C++ are represented by the string
class, which provides a wide range of operations for working with strings.
Here’s an example code that demonstrates how to declare and initialize a string variable, and how to perform basic string operations:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
// print the length of the string
cout << "Length: " << str.length() << endl;
// print the first character of the string
cout << "First character: " << str[0] << endl;
// print the last character of the string
cout << "Last character: " << str[str.length() - 1] << endl;
// concatenate two strings
string str2 = " How are you?";
string result = str + str2;
cout << "Concatenated string: " << result << endl;
// find the position of a substring
string sub = "world";
size_t pos = str.find(sub);
if (pos != string::npos) {
cout << "Substring found at position " << pos << endl;
} else {
cout << "Substring not found" << endl;
}
return 0;
}
In the code above, we have declared and initialized a string variable str
with the value “Hello, world!”. We have then printed the length of the string using the length()
function, the first and last characters of the string using the array syntax []
, and concatenated the string with another string str2
using the +
operator.
We have also used the find()
function to search for a substring sub within the string str
, and printed its position if found. The find()
function returns the position of the first occurrence of the substring, or string::npos
if the substring is not found.
Overall, strings are an essential part of working with text data in C++, and the string
class provides many useful functions for working with them.