[英]How to remove LAST INSTANCE of a character from a string
I am building a string with StringBuilder. 我正在使用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',)
实际结果 :
INSERT INTO .... VALUES('1','2','3',)
desired outcome : INSERT INTO .... VALUES('1','2','3')
期望的结果 :
INSERT INTO .... VALUES('1','2','3')
您可以使用“删除”方法删除某个位置的特定字符:
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. 检查
if (col_no > 0)
是否有点过分,因为如果没有列,查询仍会因其他原因而失败,但如果我们认为这是一个关于如何在StringBuilder
组合字符串的模板,那么检查就是正确的事情。
Ah... Building a query in that way is the wrong thing to do. 啊......以这种方式构建查询是错误的。
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 . 但是,如果你真的想创建一个sql-query,我强烈建议使用sql-parameters来阻止sql-injection 。 So don't include the values in your sql-string.
所以不要在sql-string中包含这些值。
. 。
string query = ext.Substring(0, ext.LastIndexOf(",")) + ext.Substring(ext.LastIndexOf(",") + 1);
or this: 或这个:
string query = ext.Remove(ext.LastIndexOf(","), 1);
Try this. 尝试这个。 simple logic
简单的逻辑
Check the below if condition in befor append comma line 检查以下条件是否为befor append逗号行
**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(",");
}**
}
Replace 更换
Q.Append(",");
inside the for-loop with 在for循环中
if (i != col_no - 1)
{
Q.Append(",");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.