Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 给定一个字符串,在不使用string.replace()的情况下查找并替换为另一个字符串_C#_String_Replace_Char - Fatal编程技术网

C# 给定一个字符串,在不使用string.replace()的情况下查找并替换为另一个字符串

C# 给定一个字符串,在不使用string.replace()的情况下查找并替换为另一个字符串,c#,string,replace,char,C#,String,Replace,Char,下面是我想要实现的一个示例:例如,给定字符串某物,如果要用DDD替换所有出现的so,结果将是DDDmething 以下是我如何实施它;我的代码根据字符的特定位置查找字符并对其进行更改,但实际上我想实现我上面所述的内容 static void Main(string[] args) { string str = "The Haunting of Hill House!"; Console.WriteLine("String: " + str);

下面是我想要实现的一个示例:例如,给定字符串某物,如果要用DDD替换所有出现的so,结果将是DDDmething

以下是我如何实施它;我的代码根据字符的特定位置查找字符并对其进行更改,但实际上我想实现我上面所述的内容

    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();
    }

你可以这样做:

var someString = "This is some sort of string.";

var resultIndex = 0;
var searchKey ="So";
var replacementString = "DDD";
while ((resultIndex = someString.IndexOf(searchKey, resultIndex, StringComparison.OrdinalIgnoreCase)) != -1)
{
  var prefix = someString.Substring(0, Math.Max(0, resultIndex - 1));
  var suffix = someString.Substring(resultIndex + searchKey.Length);
  someString = prefix + replacementString + suffix;
  resultIndex += searchKey.Length;
}

预计将生成字符串的DDDme DDDrt。

这应该可以满足您的要求。其思想是使用IndexOf查找要替换的子字符串的索引,然后在子字符串之前追加子字符串,然后从找到的子字符串的末尾开始搜索。然后,在找到并替换所有子字符串后,如果有,则将原始字符串的其余部分追加到末尾

请注意,这不会对输入进行任何检查,您真的应该使用字符串。请替换,因为我相信它会更有效

public string Replace(string input, string find, string replace)
{
    // The current index in the string where we are searching from
    int currIndex = 0;

    // The index of the next substring to replace
    int index = input.IndexOf(find);

    // A string builder used to build the new string
    var builder = new StringBuilder();

    // Continue until the substring is not found
    while(index != -1)
    {
        // If the current index is not equal to the substring location
        // when we need to append everything from the current position
        // to where we found the substring
        if(index != currIndex ) 
        {
            builder.Append(input.Substring(currIndex , index - currIndex));
        }

        // Now append the replacement
        builder.Append(replace);

        // Move the current position past the found substring
        currIndex = index + find.Length;

        // Search for the next substring.
        index = input.IndexOf(find, currIndex );
    }

    // If the current position is not the end of the string we need
    // to append the remainder of the string.
    if(currIndex < input.Length) 
    {
        builder.Append(input.Substring(currIndex));
    }

    return builder.ToString();
}

另一种方法可能是按so拆分字符串,并按DDD连接生成的数组:

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

实际上,您只需要添加一个对int index=str.IndexOf的调用,然后计算出在子字符串调用中要复制多少旧字符串。您的意思是像Regex.Replaceinput、Regex.EscapesearchString、replacement、RegexOptions.IgnoreCase之类的东西?为什么不使用string.Replace方法呢?我的意思是有什么问题?@500 InternalServerError你能展示一下它的实现吗?当然,我能理解你指的是someString.IndexOfsearchKey,resultIndex不是string.IndexOf,因为它是一个实例方法。同样,对于这个固定值,它给出了类似于字符串的结果。最后,最好使用StringBuilder,而不是在循环中连接字符串。是的,我的错。我修好了。StringBuilder在这方面做得太过火了。性能方面。如果现在运行它,当resultIndex为0时失败,那么Math.Min0,resultIndex-1为-1,这是无效的长度,无法传递给Substring.Yes。我没有检查或测试它。应该是数学,而不是马克斯。我修好了。非常感谢。需要一些复制和粘贴修复了。替换了搜索变量我不明白,字符串声明在哪里?你能举一个实际的例子并打印出来吗?这是一个方法,你会像字符串结果=替换某种东西一样使用它,所以,da;要获得damething的dame dart。谢谢,但我想我会选择@Slai answer,因为它只是一行代码。它显示了一个错误,无法从字符串[]转换为字符。我如何计算已经进行了多少更改,或者找到了多少次匹配?@bimixbimix.Length-1数组结果来自。SplitI尝试了var count=array.Length-1;但它打印的是32,这是不正确的。