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

C#String

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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('&');

Solution 2 - C#

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.

Solution 3 - C#

string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
    dest = source.Substring(0, source.Length - 1);
}

Solution 4 - C#

Try this:

paramstr.Remove((paramstr.Length-1),1);

Solution 5 - C#

I would just not add it in the first place:

 var sb = new StringBuilder();

 bool first = true;
 foreach (var foo in items) {
    if (first)
        first = false;
    else
        sb.Append('&');
    
    // for example:
    var escapedValue = System.Web.HttpUtility.UrlEncode(foo);

    sb.Append(key).Append('=').Append(escapedValue);
 }

 var s = sb.ToString();

Solution 6 - C#

string str="This is test string.";
str=str.Remove(str.Length-1);

Solution 7 - C#

It's better if you use string.Join.

 class Product
 {
   public int ProductID { get; set; }
 }
 static void Main(string[] args)
 {
   List<Product> products = new List<Product>()
      {   
         new Product { ProductID = 1 },
         new Product { ProductID = 2 },
         new Product { ProductID = 3 }
      };
   string theURL = string.Join("&", products.Select(p => string.Format("productID={0}", p.ProductID)));
   Console.WriteLine(theURL);
 }

Solution 8 - C#

It's good practice to use a StringBuilder when concatenating a lot of strings and you can then use the Remove method to get rid of the final character.

StringBuilder paramBuilder = new StringBuilder();

foreach (var item in itemsToAdd)
{
	paramBuilder.AppendFormat(("productID={0}&", item.prodID.ToString());
}

if (paramBuilder.Length > 1)
	paramBuilder.Remove(paramBuilder.Length-1, 1);

string s = paramBuilder.ToString();

Solution 9 - C#

paramstr.Remove((paramstr.Length-1),1);

This does work to remove a single character from the end of a string. But if I use it to remove, say, 4 characters, this doesn't work:

paramstr.Remove((paramstr.Length-4),1);

As an alternative, I have used this approach instead:

DateFrom = DateFrom.Substring(0, DateFrom.Length-4);

Solution 10 - C#

Add a StringBuilder extension method.

public static StringBuilder RemoveLast(this StringBuilder sb, string value)
{
    if(sb.Length < 1) return sb;
    sb.Remove(sb.ToString().LastIndexOf(value), value.Length);
    return sb;
}

then use:

yourStringBuilder.RemoveLast(",");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionremView Question on Stackoverflow
Solution 1 - C#Brian RasmussenView Answer on Stackoverflow
Solution 2 - C#Rob Fonseca-EnsorView Answer on Stackoverflow
Solution 3 - C#Steve TownsendView Answer on Stackoverflow
Solution 4 - C#Nelson T JosephView Answer on Stackoverflow
Solution 5 - C#Marc GravellView Answer on Stackoverflow
Solution 6 - C#Altaf PatelView Answer on Stackoverflow
Solution 7 - C#Cheng ChenView Answer on Stackoverflow
Solution 8 - C#Dan DiploView Answer on Stackoverflow
Solution 9 - C#Uzair Zaman SheikhView Answer on Stackoverflow
Solution 10 - C#Md Nazmoon NoorView Answer on Stackoverflow