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\"
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);
//
var query = "SELECT * FROM People WHERE City = @City AND County = @County AND";
var scrubbed = query.Substring(0, query.Length - 4);
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);
Another way:
string myString = "SELECT * FROM People WHERE City = @City AND County = @County AND";
myString = myString.TrimEnd(" AND".ToCharArray());
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.
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.)