klce
klce

Reputation: 220

Insert space before number in PascalCase string

I want to place a space before a number.

Say for example I have this PascalCase string: "SupportContactAddressLine1".

I want it to display "Support Contact Address Line 1"

I have tried this:

var s = PascalCase;

 for (var i = 1; i < s.Length; i++)
 {
  if (char.IsLower(s[i - 1]) && char.IsUpper(s[i]))
  {
    s = s.Insert(i, " ");
  }
 }

But the result is: "Support Contact Address Line1"

Upvotes: 0

Views: 538

Answers (3)

Karthik D V
Karthik D V

Reputation: 926

This should help you:

var res = Regex.Replace("SupportContactAddressLine100", "([A-Z])|([0-9]+)", " $1$2");

Upvotes: 0

John Willemse
John Willemse

Reputation: 6698

A digit is not a letter, therefore there is no distinction between lower case and upper case, and char.IsUpper('1') returns false.

You should include the use of char.IsDigit(...) to check for digits.

Upvotes: 0

Guffa
Guffa

Reputation: 700800

Check for a digit too:

if (Char.IsLower(s[i - 1]) && (Char.IsUpper(s[i]) || Char.IsDigit(s[i])))

Upvotes: 2

Related Questions