如何将一个字符串放在另一个字符串中,而不是将字符放在某个索引处

How to place a string inside another string , instead of the character at some index

本文关键字:字符串 字符 索引 一个 另一个      更新时间:2023-10-16

如果我有:Enter(x)

并且我想在(后面放置room2,但是没有x,那么std::insert不起作用自if:

std::string myString = "Enter(x)";
std::string placeMe = "room2";
myString.insert(myString.find_first_of("(") + 1 , placeMe);

那么我得到:Enter(room2x)

如何将placeMe 替换为某个索引的 ?

我相信你正在寻找的功能是替换而不是插入。

http://www.cplusplus.com/reference/string/string/replace/

首先,您可能想要find而不是find_first_of,因为您只想匹配一个可能的子字符串。其次,您需要std::string::replace函数:

myString.replace(myString.find("(") + 1, 1, placeMe);