In C++, strings are sequences of characters represented by the std::string
class from the Standard Template Library (STL). Strings in C++ are powerful and versatile, offering a wide range of operations and utilities for manipulating and working with text data efficiently. Here’s an overview of strings in C++:
Definition: A string in C++ is a sequence of characters stored as a contiguous array. It is represented by the std::string
class, which provides a rich set of operations and utilities.
Initialization: Strings can be initialized in various ways:
std::string str1 = "Hello"; // Initialized with a literal std::string str2("World"); // Initialized with a constructor std::string str3 = str1 + " " + str2; // Concatenation
Accessing Characters: Characters in a string can be accessed using array notation or iterators:
std::string str = "Hello"; char firstChar = str[0]; // Accessing first character
Length: The length of a string can be obtained using the length()
or size()
member functions:
std::string str = "Hello"; int len = str.length(); // len = 5
Concatenation: Combining two strings using the +
operator or append()
function.
std::string str1 = "Hello"; std::string str2 = "World"; std::string result = str1 + " " + str2; // "Hello World"
Substring: Extracting a part of the string using substr()
function.
std::string str = "Hello World"; std::string substr = str.substr(6, 5); // "World"
Searching: Searching for substrings or characters using find()
or find_first_of()
functions.
std::string str = "Hello World"; size_t found = str.find("World"); // found = 6
Modification: Modifying characters or sections of the string directly.
std::string str = "Hello"; str[0] = 'J'; // "Jello"
#include#include int countOccurrences(const std::string& str, char target) { int count = 0; for (char ch : str) { if (ch == target) { count++; } } return count; } int main() { std::string str = "Hello, World!"; char target = 'l'; int count = countOccurrences(str, target); std::cout << "Occurrences of '" << target << "': " << count << std::endl; return 0; }
#include#include #include bool isPalindrome(const std::string& str) { std::string reversed = str; std::reverse(reversed.begin(), reversed.end()); return str == reversed; } int main() { std::string str = "madam"; if (isPalindrome(str)) { std::cout << str << " is a palindrome." << std::endl; } else { std::cout << str << " is not a palindrome." << std::endl; } return 0; }