Code Example:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
size_t pos = str.find(",");
if (pos != std::string::npos) {
std::string substr = str.substr(pos + 1);
std::cout << "Substring after comma: " << substr << std::endl;
}
return 0;
}
Explanation:
- Include the necessary header files for input/output and string manipulation.
- Define the main function as the entry point of the program.
- Create a string variable "str" and initialize it with the value "Hello, World!".
- Use the
find
method of the string class to locate the position of the comma within the string. If the comma is found, store its position in the variable "pos". - Check if the comma is found by comparing the position with
std::string::npos
, which indicates "not found". - If the comma is found, use the
substr
method to extract the substring starting from the position after the comma. - Output the extracted substring after the comma to the console.
- Return 0 to indicate successful program execution.