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

前端 未结 10 1895
一个人的身影
一个人的身影 2020-12-23 00:21

Building a string for post request in the following way,

  var itemsToAdd = sl.SelProds.ToList();
  if (sl.SelProds.Count() != 0)
  {
      foreach (var item         


        
相关标签:
10条回答
  • 2020-12-23 00:43
    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);
    
    0 讨论(0)
  • 2020-12-23 00:51

    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);
     }
    
    0 讨论(0)
  • 2020-12-23 00:51

    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('&');
    
    0 讨论(0)
  • 2020-12-23 00:55

    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();
    
    0 讨论(0)
  • 2020-12-23 00:55

    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.

    0 讨论(0)
  • 2020-12-23 00:57

    Try this:

    paramstr.Remove((paramstr.Length-1),1);
    
    0 讨论(0)
提交回复
热议问题