给定一个字符串查找出现的位置并替换为另一个字符串而不使用string.replace() [英] Given a string find occurrences and replace with another string without using string.replace()

查看:162
本文介绍了给定一个字符串查找出现的位置并替换为另一个字符串而不使用string.replace()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我要实现的示例:例如,给定字符串某事,如果要替换所有出现的 so 与DDD ,结果将为 DDD方法

Here is an example of what I want to implement: for instance, given the string Something, if you were to replace all occurrences of so with DDD, the result would be DDDmething.

这是我实现它的方式;我的代码按其特定位置找到了一个字符并对其进行了更改,但实际上我想实现上面所说的内容。

Here is how I am implementing it; my code finds a char by its specific position and changes it, but in fact I want to implement what I stated above.

    static void Main(string[] args)
    {
        string str = "The Haunting of Hill House!";
        Console.WriteLine("String: " + str);

        // replacing character at position 7
        int pos = 7;
        char rep = 'p';

        string res = str.Substring(0, pos) + rep + str.Substring(pos + 1);
        Console.WriteLine("String after replacing a character: " + result);

        Console.ReadLine();
    }


推荐答案

替代方案可能是拆分按 so字符串,并按 DDD加入结果数组:

Alternative might be to split the string by "so" and join the resulting array by "DDD" :

string result = string.Join("DDD", "something".Split(new[] { "so" }, StringSplitOptions.None));

这篇关于给定一个字符串查找出现的位置并替换为另一个字符串而不使用string.replace()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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