-2

I'm new in programming and this is my first project and I'm using C#. Basically I tryed to do a function that insert one more single quote in string that already have a single quote, but this is crashing my program and I don't know why.

The function:

private string CheckSingleQuote(string txt)
{
    for (int i = 0; i < txt.Length; i++)
        if (txt[i] == '\'')
            txt = txt.Insert(i, "'");
    return txt;
}

When I click in a specific button, this function is called ten times to set the value of the strings.

  • 1
    If you find a quote you add a new one. Then you go to the next character and find the quote you just added. So you add a new one. Then you go to the next character and find the quote you just added. So you add a new one. etc etc – mjwills May 07 '21 at 02:37
  • What you want to do instead is call `String.Replace` once. Or if you really want to persist with this strange approach, iterate through the string in reverse. – mjwills May 07 '21 at 02:37
  • 1
    Can I ask _why_ you are using this function? You aren't using it to build SQL strings are you? – mjwills May 07 '21 at 03:25
  • @mjwills Oh yes, I didn't notice that. Thanks! And yes, I'm using this to call INSERT/UPDATE SQL Querys, unfortunately with my low knowledge this was the only way I thought for querys in varchar. – Pedro Henrique May 07 '21 at 15:29
  • 1
    OK then the duplicate is wrong. The correct duplicate is https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection . **You need to stop calling that function you are using to build SQL right now**. – mjwills May 08 '21 at 00:35

1 Answers1

0

You can do String.Replace("'", "''") or if you want to use the for:

private string CheckSingleQuote(string txt)
{
    for (int i = 0; i < txt.Length; i++)
        if (txt[i] == '\'')
            txt = txt.Insert(i++, "'");
    return txt;
}

As mjwills said in the comment the i++ is to skip the ' character that you just inserted.

  • 1
    @Pedro do not do this if you are creating a SQL string, it will open your code to [SQL injection](https://owasp.org/www-community/attacks/SQL_Injection). You need to [use parameters](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection). – Dour High Arch May 14 '21 at 20:38
  • @DourHighArch I didn't know why he needed it. He wrote that comment after my answer. I just answered his question. – Afshin Mobayen Khiabani May 14 '21 at 21:29