Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete last character in a string in C#?

Tags:

string

c#

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#?

like image 304
rem Avatar asked Sep 19 '10 13:09

rem


People also ask

How do I remove the last symbol from a string?

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.

How do I remove the last 3 characters from a string?

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.

How do you get rid of the first and last character in a string C?

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.

How do you delete a letter from a string C?

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.


2 Answers

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('&'); 
like image 108
Brian Rasmussen Avatar answered Sep 22 '22 17:09

Brian Rasmussen


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.

like image 27
Rob Fonseca-Ensor Avatar answered Sep 23 '22 17:09

Rob Fonseca-Ensor