C#: How to detect . in string and insert a space after it/How to insert space after n chars

cstring

Suppose I have a long string like 4600airportburlingame150anzablvd.burlingamecalifornia94010. My code is breaking on this string. This is unusual, 99% of entries will not have a period. The CSS in the browser wraps if there are spaces in the string and there isn't any here.

  1. How do I detect the period (".") and insert a space directly after it? Remember 99% of strings will not have a period in them. The code has to detect if it has a period and if so, do the insertion, otherwise not.
  2. If I determine a maximum string length, how do I insert a space at some length?

Best Answer

To insert a space after every dot:

var newString = oldString.Replace(".", ". ");

To insert a space after every dot except for the dots that already have a space or dots at the end of the string:

var newString = Regex.Replace(oldString, @"\.(?! |$)", ". ");

To insert a space after every n characters:

var newString = Regex.Replace(oldString, new string('.', n), m => m.Value + " ");