using System;
using System.Text;
namespace Sample
{
internal static class StringExtentions
{
public static string CustomReplace(this string origin, string from, string to, StringComparison stringComparison = StringComparison.Ordinal)
{
var sb = new StringBuilder();
int position = 0;
do
{
var quoteStart = origin.IndexOf('"', position);
if (quoteStart == -1)
quoteStart = origin.Length;
var headLength = quoteStart - position;
if (headLength > 0)
{
sb.Append(origin.Substring(position, headLength).Replace(from, to, stringComparison));
}
position = quoteStart;
if(position == origin.Length) break;
var quoteEnd = origin.IndexOf('"', position + 1);
if (quoteEnd == -1)
quoteEnd = origin.Length;
var tailLength = quoteEnd + 1 - position;
if (tailLength > 0)
{
sb.Append(origin.Substring(position, tailLength));
}
position = quoteEnd + 1;
} while (position < origin.Length);
return sb.ToString();
}
}
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Я сказал: \"БАНАН не банан\", но банан не согласен со мной. Но я отвечу этому банану: \"бананством\"".CustomReplace("банан", "яблоко", StringComparison.OrdinalIgnoreCase));
}
}
}