Trying to Add Spaces Between Characters in a String in C#

How to insert a space into a string, between every 4 characters?

Assuming that it's fine to work from right-to-left, this should do the trick:

displaynum_lbl.Text = System.Text.RegularExpressions.Regex.Replace(printClass.mynumber.ToString(), ".{4}", "$0 ");

You can find that and a good deal more information in other StackOverflow answers, example: Add separator to string at every N characters?

Adding spaces between character in a String C#

You can use Linq, first Aggregate the string by adding spaces then use Replace to remove the space on the right of each hyphen.

string initial = "~(((-P|-Q)->(P->Q))&((P->Q)->(-P|Q)))";
string result = initial.Aggregate("", (c, i) => c + i + ' ').Replace(" - ", " -").Trim();

How to add space in string in c#

PadLeft and PadRight will only add padding it the string is shorter that then number of padding characters you want to add. Since Advertising is 11 characters long and you are padding to 10 characters the string won't change.

If you just want to add a prefix and suffix to a piece of string then you can do this:

string txt = "Advertising";

var padding = new string(' ', 10);
var newText = string.Concat(padding, txt, padding);

Put space between digits in C#

var withoutSpaces = new Random().Next(10000, 100000);
string withSpaces = "";
for (int i = 0; i < withoutSpaces.ToString().Length; i++)
{
string test = withoutSpaces.ToString().ElementAt(i) + " ";
withSpaces += test;
}
string WithSpacesFinal = withSpaces.Trim();

This should do it for you

Insert space between characters

Don't use StringSplitOptions.RemoveEmptyEntries

string aString = "a,aaa,aaaa,aaaaa,,,,,";
var newStr = String.Join(", ", aString.Split(','));


Related Topics



Leave a reply



Submit