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?
Asked
Active
Viewed 174 times
-2

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
-
1Though `AsEnumerable` works, my preference here would instead be either `string.Join(' ', (IEnumerable
)whatever)` or `string.Join – Eric Lippert Apr 25 '20 at 01:00(' ', whatever)`. Do you see why these do the same thing? -
@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
-
1All 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 Answers
-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
-
Though this works, it allocates an unnecessary extra copy of the string. Do you see how to make this work without allocating any extra memory other than the new string? – Eric Lippert Apr 25 '20 at 00:54
-
-
Well, reason it out. **Why did you say `ToCharArray` in the first place**? – Eric Lippert Apr 25 '20 at 01:34
-
Just because of the method signature, I need an IEnumerable
or an IEnumerable – fsbflavio Apr 25 '20 at 02:00to pass to it. -
ok, if I use ```string.Join
(" ", "test123"); ``` I won't need to call ToCharArray who creates a string copy. Is that the point? – fsbflavio Apr 25 '20 at 02:05