По заданной строке найдите вхождения и замените ее на другую без использования string.replace () - PullRequest
1 голос
/ 06 июля 2019

Вот пример того, что я хочу реализовать: например, учитывая строку Something, если бы вы заменили все вхождения so на DDD, результатом будет 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();
    }

Ответы [ 3 ]

1 голос
/ 06 июля 2019

Это должно делать то, что вы хотите.Идея состоит в том, чтобы использовать IndexOf, чтобы найти индекс подстроки для замены, затем добавить подстроку до того, как за ней последует замена, а затем начать поиск с конца найденной подстроки.Затем, после того как все подстроки найдены и заменены, добавьте оставшуюся часть исходной строки в конец, если она есть.

Обратите внимание, что это не делает никаких проверок на входе, и вы действительно должны использовать string.Replace какЯ уверен, что это более производительный.

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();
}
1 голос
/ 06 июля 2019

Альтернативой может быть разделение строки на «so» и присоединение полученного массива на «DDD»:

string result = string.Join("DDD", "something".Split(new[] { "so" }, StringSplitOptions.None));
0 голосов
/ 06 июля 2019

Вы можете сделать это так:

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 строки." .

...