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

前端 未结 10 1896
一个人的身影
一个人的身影 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 01:00
    string str="This is test string.";
    str=str.Remove(str.Length-1);
    
    0 讨论(0)
  • 2020-12-23 01:02
    string source;
    // source gets initialized
    string dest;
    if (source.Length > 0)
    {
        dest = source.Substring(0, source.Length - 1);
    }
    
    0 讨论(0)
  • 2020-12-23 01:05

    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(",");
    
    0 讨论(0)
  • 2020-12-23 01:06

    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();
    
    0 讨论(0)
提交回复
热议问题