String Manipulation
String manipulation refers to the process of performing operations on strings, such as accessing individual characters, finding substrings, concatenating strings, and more. In C++, the std::string
class provides a convenient way to work with strings.
To start with string manipulation in C++, first, include the <string>
library. Here's an example program that demonstrates some common string operations:
TEXT/X-C++SRC
1{{code}}
In this example:
- We create a string variable
message
and initialize it with the value "Hello, world!" - We use the
length()
function to get the length of the string and print it - We access individual characters of the string using the indexing operator (
[]
) - We append another string to
message
using the+=
operator - We find a substring (
word
) within another string (sentence
) using thefind()
function and print the index where it is found
You can run the above program and observe the output to see the results of these string operations. Feel free to experiment and modify the code to further explore string manipulation in C++.
xxxxxxxxxx
31
}
int main() {
// Create a string variable
std::string message = "Hello, world!";
// Print the length of the string
std::cout << "Length: " << message.length() << std::endl;
// Access individual characters
std::cout << "First character: " << message[0] << std::endl;
std::cout << "Last character: " << message[message.length() - 1] << std::endl;
// Append to the string
std::string name = "Alice";
message += " My name is " + name;
std::cout << "Updated message: " << message << std::endl;
// Find substrings
std::string sentence = "This is a sentence.";
std::string word = "sentence";
size_t found = sentence.find(word);
if (found != std::string::npos) {
std::cout << "Word found at index: " << found << std::endl;
} else {
std::cout << "Word not found." << std::endl;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment