英文:
C++ cut out part of std::string and assign another one
问题
Sure, here is the translated code portion:
我想获取 std::string 的一部分,将该部分赋值给另一个空的 std::string,然后从原始字符串中删除该部分。我想知道如何在一行中完成这个操作?
是否有字符串方法可以做类似的事情?->
std::cout << oldStr; // "Hello world!";
std::string newStr = oldStr.someMethod("Hello");
std::cout << newStr; // "Hello"
std::cout << oldStr; // " world!";
请注意,这里的 oldStr.someMethod("Hello")
是一个示例,实际上需要使用适当的代码来实现这个操作,这不是标准字符串方法的一部分。
英文:
I want to get part of a std::string, assign that part to another empty std::string, and then remove that part from the original string. I wonder how to do it in one line?
Is there any string methods to do something like that ? ->
std::cout << oldStr; // "Hello world!";
std::string newStr = oldStr.someMethod("Hello");
std::cout << newStr; // "Hello"
std::cout << oldStr; // " world!"
答案1
得分: 3
If you know the exact string you can use the substring method substr
std::string oldStr = "Hello world!";
std::cout << oldStr << std::endl; // "Hello world!"
std::string newStr = oldStr.substr(0, 5);
oldStr = oldStr.substr(6);
std::cout << newStr << std::endl; // "Hello"
std::cout << oldStr << std::endl; // " world!"
英文:
If you know the exact string you can use the substring method substr
std::string oldStr = "Hello world!";
std::cout << oldStr << std::endl; // "Hello world!"
std::string newStr = oldStr.substr(0, 5);
oldStr = oldStr.substr(6);
std::cout << newStr << std::endl; // "Hello"
std::cout << oldStr << std::endl; // " world!"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论