简体   繁体   中英

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?

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)

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM