How to remove a LAST INSTANCE 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 get a "," at the end of my line. I tried to use

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

to remove the excess "," , but it also removes the ")" .

How to remove only the last comma?

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

Desired result : INSERT INTO .... VALUES('1','2','3')

+6
source share
6 answers

It:

 Q.Append(")"); 

replace

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

Checking if (col_no > 0) bit overboard, because if there is no column, the request will still work for other reasons, but if we look at this template on how to combine strings in StringBuilder , then checking is the right thing.

Ah ... Creating a query this way is the wrong thing.

+2
source

You can use the Delete method to delete a specific character at a position:

 query = query.Remove(query.LastIndexOf(","), 1); 
+13
source

I would suggest removing the comma first before adding the last one ) , therefore:

 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 recommend using sql parameters to prevent sql injection . Therefore, do not include the values โ€‹โ€‹in your sql string.

+1
source
  • The right way to achieve your goal is to use a parameterized query.
  • it is possible to delete the last coma before putting the bracket
  • The clean answer to your question may be as follows:

.

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

or that:

 string query = ext.Remove(ext.LastIndexOf(","), 1); 
0
source

Try it. simple logic

Check below if the condition for adding a comma string

  **if(i!=(col_no-1)) { Q.Append(","); }* 

With your code.

  for (i = 0; i < col_no; i++) { Q.Append("'"); Q.Append(col_value[i]); Q.Append("'"); **if(i!=(col_no-1)) { Q.Append(","); }** } 
0
source

Replace

  Q.Append(","); 

inside a for loop with

  if (i != col_no - 1) { Q.Append(","); } 
0
source

Source: https://habr.com/ru/post/952087/


All Articles