在C ++ / CLI中只替换一个字符串

时间:2014-11-16 11:55:19

标签: .net replace c++-cli

我的文字如下:

String^ txt="hello kitty hello master and You, hello kitty and other";
String^ txtst="hello kitty";

并且只想在文本中替换第一个问候语。

String^ after = spin->Replace(txt,txtst);

替换我所有的琴弦" hello kitty"我只需要一个。

需要帮助:(

3 个答案:

答案 0 :(得分:2)

由于内置String::Replace将替换所有出现的内容,因此我会编写一个帮助方法来替换所有出现的方法。

使用IndexOf查找字符串的第一个匹配项SubString以获取字符串左侧和右侧的部分,并将它们与+连接在一起(由编译器转换为String::Concat

String^ ReplaceOne(String^ s, String^ searchFor, String^ replaceWith)
{
    int index = s->IndexOf(searchFor);
    if (index == -1) return s; // search string was not found.
    return s->SubString(0, index) + replaceWith + s->SubString(index + searchFor->Length);
}

答案 1 :(得分:0)

试试这个:

String^ after = spin->Replace(txt,txtst,1);

答案 2 :(得分:-1)

这将用指定的替换字符串替换第一个找到的字符串。

bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

std::string string("hello $name");
replace(string, "$name", "Somename");
相关问题