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"
I want to remove the last AND programatically, how can I do that?
Thanks
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
string myString = "SELECT * FROM People WHERE City = @City AND County = @County AND";
Console.WriteLine(myString.Substring(0, myString.LastIndexOf(' ')));
But you may also consider building your AND-clause without the last AND from the beginning.
List<string> andConditions = new List<string>();
andConditions.Add("City = @City");
andConditions.Add("County = @County");
string myString = "SELECT * FROM People WHERE " + string.Join(" AND ", andConditions);
Method 2
Multiple methods for fixing the string given already.
This looks like dynamically generated SQL, so, the more sensible solution in my mind is to never have the final AND there. This can be done by counting the number of parameters you’ve added to the where clause, and prepending the and for every parameter after the first.
Method 3
var query = "SELECT * FROM People WHERE City = @City AND County = @County AND"; var scrubbed = query.Substring(0, query.Length - 4);
Method 4
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.)
Method 5
also, can be done via
//............
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);
//
Method 6
Another way:
string myString = "SELECT * FROM People WHERE City = @City AND County = @County AND";
myString = myString.TrimEnd(" AND".ToCharArray());
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0