94

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

2
  • 2
    Guess it's better to just not add it in the first place, but otherwise you can try paramstr.Substring(0, paramstr.Length - 1) Commented Sep 19, 2010 at 15:29
  • In case your prodID is allowed to contain arbitrary characters, especially &, you need to make sure it gets properly escaped, like e.g. the answer of @MarcGravell does. Commented Aug 14, 2015 at 3:04

10 Answers 10

241

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('&');
Sign up to request clarification or add additional context in comments.

5 Comments

Be aware that TrimEnd will remove all trailing occurrences of that character '&'... so if the string ends with '&&&' then TrimEnd will remove all 3 of those '&', not just the last one. That may or may not be what the OP wants.
@DougS FWIW I did writer "remove one (or more)".
+1 for a simple solution, that can thus be easily used as a component for other problems. I was searching for a solution to creating a path from multiple parts ensuring I did not have double or missing slashes. Combining TrimEnd and TrimStart with this technique ensures this.
@Joeppie: suggest using Path.Combine, which understands all path separators. Leastways use Trim which does start and end in one go.
@Nigel the trouble I have with Path.Combine is that if the second argument starts with a slash, it is interpreted as an absolute path, and the result is the absolute path; this is something I prefer to 'save' people calling my code from. Good point on the Trim, though :)
76

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.

4 Comments

Worth noting that this is helpful if you don't want to have an & sign at the end of the string.
I knew this was in Ruby, had no idea it was in C# and I'm a .net dev. I feel so embarrassed lol
I can't believe this was the chosen answer... the one just below this by @BrianRasmussen is so much simpler.
@FastTrack It solved the root problem, versus answering the question in the title. My complaint: if you are going to be fluent, why not just do it all in one line.
22
string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
    dest = source.Substring(0, source.Length - 1);
}

Comments

15

Try this:

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

2 Comments

Would you consider explaining your answer a little bit, so that others who come along have a better idea why you suggested it?
The answer by @Altaf Patel uses the sibling method String.Remove Method (Int32) which is arguably more straightforward in this situation. However, its good to know about String.Remove Method (Int32, Int32) which offers the ability to trim a substring of arbitrary length from anywhere within the source string.
13

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

4 Comments

I won't say anything about the readability of this snippet, but this is the way I'd do it.
It's also cheap and easy to just shorten the StringBuilder's length by one after the loop is done.
+1 for not adding it instead of removing it, for using a StringBuilder instead of +=, and for chaining appends instead of concatenating and appending. :)
The problem with this solution is that the "if" operator is called "n" times.
11
string str="This is test string.";
str=str.Remove(str.Length-1);

1 Comment

From String.Remove Method (Int32): "Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted."
7

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

3 Comments

You are missing .ToArray() in your Join statement. +1 though. Helped me.
@desaivv: No, I was using this overload: public static string Join<T>(string separator, IEnumerable<T> values), it's new in C# 4.0 :)
Ahh my bad. Still using VS2008 with 3.0
5

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

1 Comment

I also remembered you can use paramBuilder.Length - 1 to remove the last character, too.
1
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);

1 Comment

Using String.Remove Method (Int32, Int32), to remove 4 characters from the end of a string: result = source.Remove((source.Length - 4), 4);.
0

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(",");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.