trim string at the end of the string

前端 未结 6 781
时光说笑
时光说笑 2021-01-16 07:01

Hello I want to remove the last word from my sentence in C#. Here is my query:

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


        
6条回答
  •  爱一瞬间的悲伤
    2021-01-16 07:45

    If the final word is always going to be "AND":

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

    Or, if you need to truncate everything beyond the final space:

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

    (Although, as Donnie says, the real correct answer is to not append the superfluous final word to your string in the first place.)

提交回复
热议问题