Laziale
Laziale

Reputation: 8225

trim string at the end of the string

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

Upvotes: 1

Views: 9916

Answers (6)

Craig Curtis
Craig Curtis

Reputation: 863

Another way:

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

Upvotes: 0

Greg
Greg

Reputation: 9

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);
//

Upvotes: 0

LukeH
LukeH

Reputation: 269288

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.)

Upvotes: 2

Donnie
Donnie

Reputation: 46903

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.

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245389

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

Upvotes: 1

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

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);

Upvotes: 21

Related Questions