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')
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 .
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.
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.
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.
You can use the "Remove" method to remove a specific character at a position:
query = query.Remove(query.LastIndexOf(","), 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With