Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Replace is not working as expected

Tags:

string

c#

I have a program

    public void TestMethod2()
    {
        string[] keywords =
        {
            "SELECT", "FROM", "WHERE", "GROUP", "HAVING", "ORDER", "LEFT",  "RIGHT", "JOIN", "INNER", "OUTER", "ASC",
            "DESC", "AND", "OR","IN", "BETWEEN", "BY", "NOT", "ON", "AS", "CASE", "WHEN", "ELSE", "UPDATE", "SET"
        };

        var actualString = "SELECT * FROm A Join B On C in D case e join t left outer join inner join right join";

        foreach (var text in actualString.Split(' '))
        {
            var isExists = keywords.Any(x => x.Equals(text, StringComparison.OrdinalIgnoreCase));

            if (!isExists)
            {
                continue;
            }

            actualString = actualString.Replace(text, text.ToUpper());
        }


        var expectedString = "SELECT * FROM A JOIN B ON C IN D CASE e JOIN t LEFT OUTER JOIN INNER JOIN RIGHT JOIN";

    }

I am a newbie in C#. I am not clear why the Replace() method is not working as expected. It is showing the output SELECT * FROM A JOIN B ON C IN D CASE e joIN t LEFT OUTER joIN INner joIN RIGHT joIN

Can someone please enlighten me why Replace() is behaving like this? Thanks in advance.

like image 473
Noor A Shuvo Avatar asked Sep 24 '26 16:09

Noor A Shuvo


1 Answers

If you debug it you will notice that your keyword "in" replaces second join so you get joIN. Later your text variable will try to replace "join" with "JOIN" but it won't find "join" because part of it was uppercased.

like image 138
MistyK Avatar answered Sep 26 '26 05:09

MistyK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!