-2

I would like to know how I can insert spaces between every letter in a certain string. E.g. test123 turns into t e s t 1 2 3, Does anyone know?

GamingMidi
  • 25
  • 4
  • 5
    `string output = string.Join(" ", "test123".ToCharArray());` Or `"test123".AsEnumerable()`. – Jimi Apr 24 '20 at 22:45
  • This worked, Thank you! – GamingMidi Apr 24 '20 at 23:56
  • @Jimi: The first solution is not very efficient; do you see why? – Eric Lippert Apr 25 '20 at 00:59
  • 1
    Though `AsEnumerable` works, my preference here would instead be either `string.Join(' ', (IEnumerable)whatever)` or `string.Join(' ', whatever)`. Do you see why these do the same thing? – Eric Lippert Apr 25 '20 at 01:00
  • @Eric Lippert I'm more used to build strings like [this](https://stackoverflow.com/a/59441301/7444103). Here, it can be `var output = "test123".Aggregate(new StringBuilder(), (sb, c) => sb.Append(new[] { c, ' ' }));`. `string.Join()` has some difficulties joining chars (including the separator). – Jimi Apr 25 '20 at 01:18
  • 1
    All of the above plus `Regex.Replace("test123", "(.)", "$1 ")`. No benchmarks and debatable readability, but it's nice of the language to provide multiple options. – hector-j-rivas Apr 25 '20 at 04:20

2 Answers2

-1

Start at the end of the string and keep adding a white space as you work your way to the beginning. By working backwards, you don't need to worry about changing lengths or indices. https://dotnetfiddle.net/fC0yec

int i = str.Length-1;
StringBuilder sb = new StringBuilder(str);
while(i > 0){
  sb.Insert(i, " ");
  i--;
}

string spacedOutStr = sb.ToString();
Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
-1

As said in comments, simply do that:

var result = string.Join(" ", "test123".ToCharArray());

or, to avoid an unnecessary copy string made by ToCharArray:

var result = string.Join<char>(" ", "test123");

fsbflavio
  • 664
  • 10
  • 22