0

I am trying to map two StringBuilders:

string builder1 ="abc1,abc2,abc3,abc4,abc2"
string builder2="100,30,15,102,30"

both StringBuilders count will be the same and already mapped. But I am searching for a particular number 30 and name like abc2

i.e find(30,abc2) and remove it

so I need to keep track of the comma or could anyone suggest me best practice to remove the string I don't want in the appropriate position.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
gowww
  • 139
  • 1
  • 12
  • Perhaps use a [**`Regex`**](https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex(v=vs.110).aspx)? -- [**Regular Expressions Language - Quick Reference**](https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx). – Visual Vincent Oct 19 '16 at 20:05
  • Okay will try to use regex. as i cant use array there is memory constrain. – gowww Oct 19 '16 at 20:10
  • 1
    It's cute how you think an array will use less memory than a StringBuilder. ***TEST*** before you make assumptions. – Sam Axe Oct 19 '16 at 20:11
  • No its just that there is already a reusable string builder defined. i'll try to test. – gowww Oct 19 '16 at 20:13

2 Answers2

1

Without using Regex, it's probably easier to turn the string into a list, remove the items, then recreate the list:

StringBuilder sb1 = new StringBuilder("abc1,abc2,abc3,abc4,abc2");
string find1 = "abc2";
var newList = sb1.ToString().Split(',').ToList();
newList.RemoveAll(x => x == find1);
string result = string.Join(",", newList.ToArray());

For the VB.Net version:

Dim sb1 As New StringBuilder("abc1,abc2,abc3,abc4,abc2")
Dim find1 As String = "abc2"
Dim newList As New List(Of String)(sb1.ToString().Split(","c).ToList)
newList.RemoveAll(Function(x) x = find1)
Dim result As String = String.Join(",", newList.ToArray())
LarsTech
  • 80,625
  • 14
  • 153
  • 225
1

So I see 4 cases:

  • equals to "abc2" (seems very unlikely)
  • contains ",abc2,"
  • starts with "abc2,"
  • ends with ",abc2"

Sub removeCSVvalue(sb As StringBuilder, value$)
    If sb.Length <= value.Length Then sb.Replace(value, vbNullString) : Return ' If sb = value
    sb.Replace("," & value & ",", ",")   ' Example: replace ",abc2," with ","
    Dim C = value.Length
    If sb.Length > C Then If sb(C) = "," Then If sb.ToString(0, C) = value Then sb.Remove(0, C + 1) ' If sb.StartsWith(value & ",")
    Dim L = sb.Length - C
    If sb.Length > C Then If sb(L - 1) = "," Then If sb.ToString(L, C) = value Then sb.Length = L - 1 ' If sb.EndsWith("," & value)
End Sub

P.S. this reminds me of my first downvoted answer Remove item from string array :]

Slai
  • 22,144
  • 5
  • 45
  • 53