I would like to add a space when an uppercase character or an underscore is in the string.
How do I do this?
EXAMPLE 1
Input
ThisIsAnInputString
Output (result)
This Is An Input String
EXAMPLE 2
Input
This_Is_An_Input_String
Output (result)
This Is An Input String
You can use a regular expression that matches a lower case character followed by an upper case character, with an optional underscore between:
string output = Regex.Replace(input, "([a-z])_?([A-Z])", "$1 $2");
You might want to use this to handle single character words also:
string output = Regex.Replace(input, "(?<!^)_?([A-Z])", " $1");
Underscores:
string inputString = "This_Is_An_Input_String";
string resultString = inputString.Replace('_', ' ');
Capitals:
string inputString = "ThisIsAnInputString";
//this will put a space before all capitals that are preceded by a lowercase character
string resultString = Regex.Replace(inputString, @"([a-z])([A-Z])", "$1 $2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With