i have one string in c++ how to divide it in half like this examples book a = "bo" and b…
- User
i have one string in c++ how to divide it in half
like this examples
book a = "bo" and b = "ok"
"textbook" a = "text" and b = "book"
Assistant
You can divide a string in half in C++ by using the
std::stringclass'ssubstrfunction. Here's an example of how to do it:#include <iostream> #include <string> int main() { std::string str = "book"; std::string str2 = "textbook"; std::string a, b; // Divide string into two halves size_t pos = str.find('o'); if (pos != std::string::npos) { a = str.substr(0, pos); b = str.substr(pos + 1); } else { a = str; } // Print results std::cout << "String: " << str << std::endl; std::cout << "a: " << a << std::endl; std::cout << "b: " << b << std::endl; // Divide string into two halves pos = str2.find('t'); if (pos != std::string::npos) { a = str2.substr(0, pos); b = str2.substr(pos + 1); } else { a = str2; } // Print results std::cout << "String2: " << str2 << std::endl; std::cout << "a: " << a << std::endl; std::cout << "b: " << b << std::endl; return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.