In C++, a string is a sequence of characters stored in memory that can be manipulated using various string operations. C++ provides a built-in string class called std::string that makes it easy to work with strings.
Here are some basic concepts and operations related to C++ strings:
- Creating a string: You can create a string object by declaring a variable of type
std::stringand assigning a value to it. For example:
std::string str1 = "Hello"; // string with initialization
std::string str2("World"); // another string with initialization
std::string str3; // empty string
- Accessing characters: You can access individual characters in a string using the square bracket notation
[]. For example:
std::string str = "Hello"; char ch = str[0]; // access the first character 'H'
Note that strings are zero-indexed, meaning the first character has index 0.
- String length: You can get the length of a string using the
length()orsize()member functions. For example:
std::string str = "Hello"; int len = str.length(); // length of the string (5)
- Concatenation: You can concatenate two strings using the
+operator or theappend()member function. For example:
std::string str1 = "Hello";
std::string str2 = "World";
std::string str3 = str1 + " " + str2; // concatenate two strings
str1.append(" "); // append a string to the end
str1.append(str2);
- Substrings: You can extract a substring from a string using the
substr()member function. For example:
std::string str = "Hello World"; std::string sub = str.substr(6, 5); // extract "World" starting at index 6
The first argument to substr() is the starting index of the substring, and the second argument is the length of the substring.
- Comparison: You can compare two strings using the comparison operators
==,!=,<,<=,>, and>=. For example:
std::string str1 = "Hello"; std::string str2 = "World"; bool equal = (str1 == str2); // false bool less_than = (str1 < str2); // true
- Searching: You can search for a substring within a string using the
find()member function. For example:
std::string str = "Hello World";
size_t pos = str.find("World"); // find the position of "World" in the string
The find() function returns the starting index of the first occurrence of the substring in the string, or std::string::npos if the substring is not found.
These are just some basic concepts and operations related to C++ strings. There are many more features and functions available in the std::string class, so I encourage you to explore the C++ documentation to learn more.