V
V
VanBer2021-10-01 17:53:12
C++ / C#
VanBer, 2021-10-01 17:53:12

How NOT to replace a word in quotes?

I have a code that replaces words.
The msg variable is responsible for the lines. The user enters the word "Banana", and the program replaces the word with "Apple", through the Replace method.

It turns out a lot of lines like
msg = msg.Replace("Banana","Apple")
msg ​​= msg.Replace("Burger","Broccoli")

But if the user enters the following sentence:

I said: "a banana is better than a burger!"

Then the program will replace the words in quotes. And now the question is, how to find all the words inside quotes in c # and NOT REPLACE them? I've been struggling with this problem for a long time, I can't figure it out. Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-10-02
@VanBer

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question