如何仅对字符串的一部分进行字符串替换? [英] How do you perform string replacement on just a subsection of a string?

查看:80
本文介绍了如何仅对字符串的一部分进行字符串替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一种有效的方法,该方法可以像这样

I'd like an efficient method that would work something like this

对不起,我没有放我以前尝试过的东西.我现在更新了示例.

Sorry I didn't put what I'd tried before. I updated the example now.

// Method signature, Only replaces first instance or how many are specified in max
public int MyReplace(ref string source,string org, string replace, int start, int max)
{
     int ret = 0;
     int len = replace.Length;
     int olen = org.Length;
     for(int i = 0; i < max; i++)
     {
          // Find the next instance of the search string
          int x = source.IndexOf(org, ret + olen);
          if(x > ret)
             ret = x;
          else
             break;

         // Insert the replacement
         source = source.Insert(x, replace);
         // And remove the original
         source = source.Remove(x + len, olen); // removes original string
     }
     return ret;
}

string source = "The cat can fly but only if he is the cat in the hat";
int i = MyReplace(ref source,"cat", "giraffe", 8, 1); 

// Results in the string "The cat can fly but only if he is the giraffe in the hat"
// i contains the index of the first letter of "giraffe" in the new string

我要问的唯一原因是因为我想象我的实现会随着1000次替换而变慢.

The only reason I'm asking is because my implementation I'd imagine getting slow with 1,000s of replaces.

推荐答案

怎么样:

public static int MyReplace(ref string source,
    string org, string replace, int start, int max)
{
    if (start < 0) throw new System.ArgumentOutOfRangeException("start");
    if (max <= 0) return 0;
    start = source.IndexOf(org, start);
    if (start < 0) return 0;
    StringBuilder sb = new StringBuilder(source, 0, start, source.Length);
    int found = 0;
    while (max-- > 0) {
        int index = source.IndexOf(org, start);
        if (index < 0) break;
        sb.Append(source, start, index - start).Append(replace);
        start = index + org.Length;
        found++;
    }
    sb.Append(source, start, source.Length - start);
    source = sb.ToString();
    return found;
}

它使用 StringBuilder 来避免大量的中间 string s;我没有对其进行严格的测试,但是它似乎可以正常工作.当没有匹配项时,它还会尝试避免多余的 string .

it uses StringBuilder to avoid lots of intermediate strings; I haven't tested it rigorously, but it seems to work. It also tries to avoid an extra string when there are no matches.

这篇关于如何仅对字符串的一部分进行字符串替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆