C#里面trim 删除指定字符串

zhoutm 2015-07-06 10:33:34
我想用trim删除指定字符串,而不是指定字符。。

sql = "select * from examtable where";
if(examdate_comboBox.Text!="")
{
sql+=" and examdate='"+examdate_comboBox.Text+"' ";
}
if(group_comboBox.Text!="")
{
sql+=" and groupnum='"+group_comboBox.Text+"' ";
}
if(cardid_textBox.Text!="")
{
sql+=" and cardid='"+cardid_textBox.Text+"' e";// 累加
}
sql = sql.TrimEnd("where".ToCharArray());

比如我的sql语句根据不同条件进行累加,如果3个条件都不满足,sql语句最后会多出where字符串,目前我是在每个累加字符串后面加个空格,在用sql = sql.TrimEnd("where".ToCharArray());进行替换。
这个命令是将“where”变成数组,逐个字符进行比较,比如我在第三个条件加个“e“,也会被替换掉。
不知道有没有去掉指定字符的办法。

...全文
631 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhoutm 2015-07-13
  • 打赏
  • 举报
回复
引用 8 楼 ajianchina 的回复:
这样吧

string sql = "select * from examtable";
List<string> whereList = new List<string>();
if (examdate_comboBox.Text != "") whereList.Add("examdate='" + examdate_comboBox.Text + "'");
if (group_comboBox.Text != "") whereList.Add("groupnum='" + group_comboBox.Text + "'");
if (cardid_textBox.Text != "") whereList.Add("cardid='" + cardid_textBox.Text + "' e");
if (whereList.Count > 0) sql += " where " + string.Join(" and ", whereList.ToArray());
这个思路第一个看见,不错。。学习了。。 原则上累加条件最后字符是单引号,TrimEnd程序应该不会报错,但是还是觉得8楼的方法不错。
於黾 2015-07-06
  • 打赏
  • 举报
回复
而且你这个拼接方式有bug啊 即使后面有条件满足 也会拼接出where and 这种语句 你要写成where 1=1 and 条件1 and 条件2 这样就对了嘛
於黾 2015-07-06
  • 打赏
  • 举报
回复
引用 5 楼 smthgdin 的回复:
where 1=1 再拼接不就可以,就算3个都不满足sql也不会报错。
+1 这样最简单了
smthgdin_020 2015-07-06
  • 打赏
  • 举报
回复
where 1=1 再拼接不就可以,就算3个都不满足sql也不会报错。
  • 打赏
  • 举报
回复
而且拼接字符串一般用StringBuilder,有Remove方法,可以从指定索引位置开始移除指定长度
  • 打赏
  • 举报
回复
SubString Regex.Replace
  • 打赏
  • 举报
回复
Replace
86y 2015-07-06
  • 打赏
  • 举报
回复
用个特殊字符代代替不行吗,最后替换回来
ajianchina 2015-07-06
  • 打赏
  • 举报
回复
这样吧

string sql = "select * from examtable";
List<string> whereList = new List<string>();
if (examdate_comboBox.Text != "") whereList.Add("examdate='" + examdate_comboBox.Text + "'");
if (group_comboBox.Text != "") whereList.Add("groupnum='" + group_comboBox.Text + "'");
if (cardid_textBox.Text != "") whereList.Add("cardid='" + cardid_textBox.Text + "' e");
if (whereList.Count > 0) sql += " where " + string.Join(" and ", whereList.ToArray());

111,097

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧