Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 502
Anoushka Seechurn Avatar asked Aug 20 '13 07:08

Anoushka Seechurn


People also ask

How do you get the last occurrence of a character in a string?

strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .

How do I remove the last instance of a character in python?

rstrip. The string method rstrip removes the characters from the right side of the string that is given to it. So, we can use it to remove the last element of the string. We don't have to write more than a line of code to remove the last char from the string.

How do I remove the last 3 characters from a string?

To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

How do you remove the last character of a string in C?

Every string in C ends with '\0'. So you need do this: int size = strlen(my_str); //Total size of string my_str[size-1] = '\0'; This way, you remove the last char.


2 Answers

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

query = query.Remove(query.LastIndexOf(","), 1);
like image 108
Azhar Khorasany Avatar answered Sep 21 '22 00:09

Azhar Khorasany


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.

like image 28
xanatos Avatar answered Sep 22 '22 00:09

xanatos