About Lesson
C++ Strings
Strings in C++ are sequences of characters represented by the std::string
class. They are used to store and manipulate text or sequences of characters.
1. Initializing Strings
You can initialize strings using various methods:
- Direct initialization
- Using string literals
- Concatenation
Example:
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, "; // Direct initialization
std::string name = "Alice";
std::string message = greeting + name + "!"; // Concatenation
std::cout << message << std::endl;
return 0;
}
2. String Operations
C++ provides various operations to manipulate strings:
length()
: Returns the length of the string.append()
: Appends a string to the end of another string.substr()
: Extracts a substring.find()
: Finds the first occurrence of a substring.compare()
: Compares two strings.
Example:
#include <iostream>
#include <string>
int main() {
std::string sentence = "Programming in C++ is fun!";
std::cout << "Length of the string: " << sentence.length() << std::endl;
std::string part1 = "Hello, ";
std::string part2 = "World!";
part1.append(part2); // Append part2 to part1
std::cout << part1 << std::endl;
std::string sub = sentence.substr(14, 4); // Extract "C++"
std::cout << "Substring: " << sub << std::endl;
std::string searchStr = "C++";
size_t found = sentence.find(searchStr); // Find position of "C++"
if (found != std::string::npos) {
std::cout << "Found '" << searchStr << "' at position " << found << std::endl;
}
std::string str1 = "apple";
std::string str2 = "banana";
int comparison = str1.compare(str2); // Compare str1 and str2
if (comparison == 0) {
std::cout << str1 << " is equal to " << str2 << std::endl;
} else if (comparison < 0) {
std::cout << str1 << " is less than " << str2 << std::endl;
} else {
std::cout << str1 << " is greater than " << str2 << std::endl;
}
return 0;
}
3. Input and Output of Strings
Strings can be input from and output to the console using std::cin
and std::cout
:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name); // Read a line of input
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}
Conclusion
Understanding how to work with strings in C++ is essential for handling textual data effectively in programs. This chapter covered initializing strings, basic operations such as length, append, substr, find, and compare, as well as input and output operations with strings. Mastery of these concepts will enable you to manipulate and process strings in your C++ programs efficiently.
Join the conversation