Search code examples
c#asp.netstringcharactertrim

How to remove LAST INSTANCE of a character from a string


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')


Solution

  • 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.