C++ String
C++ String
Inserting and deleting characters or substrings from a string. You can use the
insert () and erase () methods of the string class to do this. For example, you
can write:
std::string s = "Hello";
s.insert (3, "p"); // Inserts "p" at position 3
s.erase (5, 1); // Erases 1 character from position 5
std::cout << s << std::endl; // Prints "Helpo"
Replacing characters or substrings in a string with another string. You can use
the replace () method of the string class to do this. For example, you can
write:
std::string s = "Hello";
s.replace (0, 2, "J"); // Replaces 2 characters from position 0 with "J"
s.replace (3, 2, "y"); // Replaces 2 characters from position 3 with "y"
std::cout << s << std::endl; // Prints "Jeyo"
Converting a string to uppercase or lowercase. You can use the toupper () and
tolower () functions from the <cctype> header to do this. For example, you can
write:
std::string s = "Hello";
for (char &c : s) // Loop through each character in s
{
c = toupper (c); // Convert to uppercase
}
std::cout << s << std::endl; // Prints "HELLO"
Reversing a string. You can use the reverse () function from the <algorithm>
header to do this. For example, you can write:
std::string s = "Hello";
std::reverse (s.begin (), s.end ()); // Reverse the string
std::cout << s << std::endl; // Prints "olleH"
Sorting a string. You can use the sort () function from the <algorithm> header
to do this. For example, you can write:
std::string s = "Hello";
std::sort (s.begin (), s.end ()); // Sort the string
std::cout << s << std::endl; // Prints "eHllo"
You can find more information and examples about these and other string
manipulation functions in C++ from these sources: 1, 2, 3, and . I hope this helps you