El Padrino El Padrino - 7 months ago 57
C# Question

Replace N number of string.Empty from a string

I have to replace white spaces with " " on a string (which can be variable in length). If this were all I need to do it would be easy, but I need to only replace white spaces at the start of a sentence/paragraph.

I thought that creating a sub-string of only the white spaces could help, but the problem I face is that there is not a unique character that start all paragraph/sentences.

How can I replace white spaces from a paragraph but only those at the beginning of it?


< >< >< >< >< >< > Hello World of strings and replacements.

Reference: Each < > stands for a white space, because the text editor on this site won't allow white spaces at the beginning of a sentence.

I want to remove the < > only


Try this.

var myString = "        Hello World .  ";

var countOfSpaces = myString.TakeWhile(c => c.Equals(' ')).Count();

var newString = string.Concat(Enumerable.Repeat("&#160;", countOfSpaces)) + myString.Substring(countOfSpaces);

DotNetFiddle: https://dotnetfiddle.net/376Fmk