修剪字符串末尾的字符串

时间:2010-11-19 15:50:14

标签: c# asp.net

您好我想从C#中的句子中删除最后一个单词。这是我的疑问:

"SELECT * FROM People WHERE City = @City AND County = @County AND"

我想以编程方式删除最后一个AND,我该怎么做? 感谢

6 个答案:

答案 0 :(得分:21)

string myString = "SELECT * FROM People WHERE City = @City AND County = @County AND";
Console.WriteLine(myString.Substring(0, myString.LastIndexOf(' ')));

但是你也可以考虑在没有最后一个AND的情况下构建你的AND子句。

List<string> andConditions = new List<string>();
andConditions.Add("City = @City");
andConditions.Add("County = @County");
string myString = "SELECT * FROM People WHERE " + string.Join(" AND ", andConditions);

答案 1 :(得分:2)

用于修复已经给出的字符串的多种方法。

这看起来像动态生成的SQL,因此,我认为更明智的解决方案是永远不会有最终的AND。这可以通过计算您添加到where子句中的参数数量来完成,并且在第一个参数之后为每个参数预先 and

答案 2 :(得分:1)

如果最后一个单词总是“AND”:

if (yourString.EndsWith(" AND"))
    yourString = yourString.Remove(yourString.Length - 4);

或者,如果您需要截断最终空间之外的所有内容:

int index = yourString.LastIndexOf(' ');
if (index > -1)
    yourString = yourString.Remove(index);

(虽然,as Donnie says,但真正正确的答案是首先不要将多余的最终单词附加到字符串中。)

答案 3 :(得分:1)

var query = "SELECT * FROM People WHERE City = @City AND County = @County AND";
var scrubbed = query.Substring(0, query.Length - 4);

答案 4 :(得分:0)

也可以通过

完成
//............
string query = SELECT * FROM People WHERE City = @City AND County = @County AND";
char[] charsAND = { 'A', 'N', 'D'};
char[] charsOR = { 'O', 'R'};
query = query.Trim().TrimEnd(charsAND).TrimEnd(charsOR);
//

答案 5 :(得分:0)

另一种方式:

string myString = "SELECT * FROM People WHERE City = @City AND County = @County AND";
myString = myString.TrimEnd(" AND".ToCharArray());