Building a string for post request in the following way,
var itemsToAdd = sl.SelProds.ToList(); if (sl.SelProds.Count() != 0) { foreach (var item in itemsToAdd) { paramstr = paramstr + string.Format("productID={0}&", item.prodID.ToString()); } } after I get resulting paramstr, I need to delete last character & in it
How to delete last character in a string using C#?
Using String. The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.
Use the String. slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.
Removing the first and last character In the example above, we removed the first character of a string by changing the starting point of a string to index position 1, then we removed the last character by setting its value to \0 . In C \0 means the ending of a string.
We have removeChar() method that will take a address of string array as an input and a character which you want to remove from a given string. Now in removeChar(char *str, char charToRemove) method our logic is written.
Personally I would go with Rob's suggestion, but if you want to remove one (or more) specific trailing character(s) you can use TrimEnd. E.g.
paramstr = paramstr.TrimEnd('&');
build it with string.Join instead:
var parameters = sl.SelProds.Select(x=>"productID="+x.prodID).ToArray(); paramstr = string.Join("&", parameters); string.Join takes a seperator ("&") and and array of strings (parameters), and inserts the seperator between each element of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With