Werner
Werner

Reputation: 2154

Elegant way to add a specific character after each char in a string

I want to print a string from the database to a page. In this database the string looks like this: "!"§%&/". In my page it should look like this: "! " § % & /" (space between the chars).

I know it's possible with a simple foreach loop and also with the Aggregate function of Linq.

Foreach loop:

var result = "";
foreach (var s in stringFromDb)
{
    result += s + " ";
}
result = result.Trim()

Aggregate function:

var result = stringFromDb.Aggregate("", (current, s) => current + (s + " ")).Trim();

The aggregate function is kinda unreadable so I will definitively not use it. Isn't there a simpler way to do this?

Upvotes: 3

Views: 1357

Answers (2)

ElectricRouge
ElectricRouge

Reputation: 1279

Try this

 string st= "!\"§%&/";
 var res = Regex.Replace(st, new string('.', 1), x => x.Value + " ");

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

Why don't you use string.Join ?

var str = "!\"§%&/";
var result = string.Join(" ", str.ToCharArray())

Or without ToCharArray (suggested in comments)

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

Upvotes: 10

Related Questions