6

Input in my case is a string with a list of elements separated by Comma

Input:

var input = "123,456,789";

Expected Output (a string):

"'123','456','789'"

I'm looking for a solution in VB.net but i'm not so familiar with it. So, I tried it in c#. Not sure what i'm missing.

My Attempt:

var input = "123,456,789";
var temp = input.Split(new Char[] { ',' });
Array.ForEach(temp, a => a = "'" + a + "'");
Console.WriteLine(String.Join(",",temp));

Actual Output:

"123,456,789"

Any help in funding a solution in vb.net is much appreciated :)

adjan
  • 13,371
  • 2
  • 31
  • 48
BetterLateThanNever
  • 886
  • 1
  • 9
  • 31
  • Any help in funding a solution in vb.net is much appreciated :) – BetterLateThanNever Dec 13 '17 at 19:48
  • 3
    Your `ForEach` is not doing what you think it's doing (it's updating a local variable `a`, not the values in the array). – juharr Dec 13 '17 at 19:49
  • because of the way strings work, when you do `a = "'" + a + "'"`, you are not replacing the value of the a. You are not changing the value of the items in the collection of strings returned by the split. You **are** creating a new string and naming it a. That leaves the items in the `temp` collection unchanged. –  Dec 13 '17 at 19:58

4 Answers4

6

You could use LINQ:

var result = string.Join(",", input.Split(',').Select(x => "'" + x + "'"))

This splits the string at the , delimiter, then adds the quotes around the pieces using Select(), and then reassembles the array using string.Join()

Edit: Here is the equivalent VB.NET solution:

Dim result As String
result = String.Join(",", input.Split(",").Select(Function (x) ("'" & x & "'" )))
adjan
  • 13,371
  • 2
  • 31
  • 48
2

input = Regex.Replace(input, "\d+", "'$0'");

JohnyL
  • 6,894
  • 3
  • 22
  • 41
0
var input = "123,456,789";
var temp = input.Split(new Char[] { ',' });
temp = Array.ConvertAll(temp, a => a = "'" + a + "'");

Console.WriteLine(String.Join(",", temp));

See also: https://stackoverflow.com/a/3867998/194717

Tony
  • 16,527
  • 15
  • 80
  • 134
0

There is a lot of solutions here but, I think, this will mach more faster:

var newStr = "'" + string.Replace(str, ",", "','") + "'";

in VB.NET

Private newStr = "'" & String.Replace(str, ",", "','") & "'"
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68