How to remove comma separated value from a string?

后端 未结 10 1801
你的背包
你的背包 2021-01-03 00:13

I want to remove a comma separated value from the string..

suppose I have a string like this

string x=\"r, v, l, m\"

and i want to

相关标签:
10条回答
  • 2021-01-03 00:45

    Its just single line of code in many ways, two of them are below:

    string x = "r,v,l,m";
    string NewX = String.Join(",", from i in x.Split(',') where  i != String.Empty && i != "v" select i);
    
    OR
    
    string NewX = String.Join(",", x.Split(',').Select(i => i.Trim()).Where(i => i != String.Empty && i != "v"));
    
    0 讨论(0)
  • 2021-01-03 00:47
    String input = "r, v, l, m, ";
    
    string itemToReplace = "v, ";
    
    string output = input.Replace(itemToReplace, string.Empty)
    
    0 讨论(0)
  • 2021-01-03 00:48

    So you want to delete an item (or replace it with a nother value) and join the string again with comma without space?

    string x = "r, v, l, m,";
    string value = "v";
    string[] allVals = x.TrimEnd(',').Split(new []{','}, StringSplitOptions.RemoveEmptyEntries);
    // remove all values:
    x = string.Join(",", allVals.Where(v => v.Trim() != value));
    // or replace these values
    x = string.Join(",", allVals.Select(v => v.Trim() == value ? "new value" : v));
    
    0 讨论(0)
  • 2021-01-03 00:49

    Just do something like:

    List<String> Items = x.Split(",").Select(i => i.Trim()).Where(i => i != string.Empty).ToList(); //Split them all and remove spaces
    Items.Remove("v"); //or whichever you want
    string NewX = String.Join(", ", Items.ToArray());
    
    0 讨论(0)
  • 2021-01-03 00:54

    Not quite sure if this is what you mean, but this seems simplest and most readable:

            string x = "r, v, l, m";
            string valueToRemove = "r";
            var result = string.Join(", ", from v in x.Split(',')
                                           where v.Trim() != valueToRemove
                                           select v);
    

    Edit: like Bob Sammers pointed out, this only works in .NET 4 and up.

    0 讨论(0)
  • 2021-01-03 00:55
    public void string Remove(string allStuff, string whatToRemove)
    {
      StringBuilder returnString = new StringBuilder();
      string[] arr = allStuff.Split('');
       foreach (var item in arr){
         if(!item.Equals(whatToRemove)){
         returnString.Append(item);
         returnString.Append(", "); 
        }
       }
      return returnString.ToString();
    }
    
    0 讨论(0)
提交回复
热议问题