How to remove LAST INSTANCE of a character from a string

12,634

Solution 1

This:

Q.Append(")");

replace with

if (col_no > 0)
{
    Q.Length--;
}

Q.Append(")");

The check if (col_no > 0) is a little overboard, because if there is no column, the query will still fail for other reasons, but if we consider this a template on how to combine strings in a StringBuilder, then the check is the right thing to do.

Ah... Building a query in that way is the wrong thing to do.

Solution 2

You can use the "Remove" method to remove a specific character at a position:

query = query.Remove(query.LastIndexOf(","), 1);

Solution 3

I would suggest to remove the comma first before you add the last ), so:

for (i = 0; i < col_no; i++)
{
    Q.Append("'");
    Q.Append(col_value[i]);
    Q.Append("'");
    Q.Append(",");

} 
if(col_no > 0) Q.Length --; // <-- this removes the last character
Q.Append(")");
string query = Q.ToString();

However, if you really want to create a sql-query i would strongly suggest to use sql-parameters to prevent sql-injection. So don't include the values in your sql-string.

Share:
12,634
Anoushka Seechurn
Author by

Anoushka Seechurn

Updated on July 06, 2022

Comments

  • Anoushka Seechurn
    Anoushka Seechurn almost 2 years

    I am building a string with StringBuilder.

    StringBuilder Q = new StringBuilder();
    Q.Append("INSERT INTO ");
    Q.Append(_lstview_item);
    Q.Append(" VALUES");
    Q.Append("("); 
    for (i = 0; i < col_no; i++)
    {
        Q.Append("'");
        Q.Append(col_value[i]);
        Q.Append("'");
        Q.Append(",");
    } 
    Q.Append(")");
    string query = Q.ToString();
    

    However, I am getting a "," at the end of my string. I tried using

    string query = ext.Substring(0, ext.LastIndexOf(",") + 1);
    

    to remove the surplus ",", but this also removes the ")".

    How can I remove the last comma only?

    actual outcome : INSERT INTO .... VALUES('1','2','3',)

    desired outcome : INSERT INTO .... VALUES('1','2','3')