Add spacing between lowercase and uppercase letters?

I would like to add a space if there is an uppercase or underscore character in the string.

How to do it?

EXAMPLE 1

Input

ThisIsAnInputString

      

Result (Result)

This Is An Input String

      

EXAMPLE 2

Input

This_Is_An_Input_String

      

Result (Result)

This Is An Input String

      

+3


source to share


6 answers


You can use a regular expression matching a lowercase character followed by an uppercase character, with an optional underscore between:

string output = Regex.Replace(input, "([a-z])_?([A-Z])", "$1 $2");

      



You can also use this to handle single characters:

string output = Regex.Replace(input, "(?<!^)_?([A-Z])", " $1");

      

+9


source


As per your requirement, you want to add a space before the uppercase character. This should also apply for the first letter. All underscores must be replaced with a space. Most of the answers here omit the first space (before This

).

var pattern = "([a-z?])[_ ]?([A-Z])";

var input = "ThisIsATest";
var output = Regex.Replace(input, pattern, "$1 $2");
// output = " This Is A Test"

var input = "This_Is_A_Test";
var output = Regex.Replace(input, pattern, "$1 $2");
// output = " This Is A Test"

var input = "ThisIsAnInputString";
var output = Regex.Replace(input, pattern, "$1 $2");
// output = " This Is An Input String"

var input = "This_Is_An_Input_String";
var output = Regex.Replace(input, pattern, "$1 $2");
// output = " This Is An Input String"

      

If you don't want any extra space at the beginning, use TrimStart

var input = "This_Is_A_Test";
var output = Regex.Replace(input, pattern, "$1 $2").TrimStart(' ');
// output = "This Is A Test"

      



Edit (updated):

I've put together various regex sentences into a small test application to test the results:

static void Main(string[] args)
{
  const string expectedResult = "This Is A Test";
  var samples = new string[][]
      {
        new [] {"This Is A Test", "This Is A Test"},
        new [] {"ThisIsATest", "This Is A Test"},
        new [] {"This_Is_A_Test", "This Is A Test"},
        new [] {"ThisIsA_Test", "This Is A Test"},
        new [] {"This_IsATest", "This Is A Test"},
        new [] {"_ThisIsATest", "This Is A Test"},
        new [] {"_This_Is_A_Test", "This Is A Test"},
        new [] {"Thi_s_Is_A_Test", "Thi s Is A Test"},
        new [] {"T hi_s_Is_A_Te s_ t", "T hi s Is A Te s  t"}
      };

  foreach (var input in samples)
  {
    Console.WriteLine(input[0] + " => " + input[1]);

    // Guffa 1 1/9 correct.
    Console.WriteLine("Guffa 1:         " + (Regex.Replace(input[0], @"([a-z])_?([A-Z])", "$1 $2") == input[1]));

    // Guffa 2 4/9 correct.
    Console.WriteLine("Guffa 2:         " + (Regex.Replace(input[0], @"(?<!^)_?([A-Z])", " $1") == input[1]));

    // Abe Miesler 1/9 correct.
    Console.WriteLine("Abe Miesler:     " + (Regex.Replace(input[0], @"([a-zA-Z])_?([A-Z])", "$1 $2") == input[1]));

    // AppDeveloper 2/9 correct. (Not entirely fair since it was not meant for underscores).
    Console.WriteLine("AppDeveloper:    " + (Regex.Replace(input[0], @"_([A-Z])", " $1") == input[1]));

    // sparky68967 1/9 correct. (Not entirely fair since it was not meant for underscores).
    Console.WriteLine("sparky68967:     " + (Regex.Replace(input[0], @"([a-z])([A-Z])", "$1 $2") == input[1]));

    // p.s.w.g 4/9 correct.
    Console.WriteLine("p.s.w.g:         " + (Regex.Replace(Regex.Replace(input[0], @"([A-Z]+)([A-Z][a-z])", "$1_$2"), "_", " ") == input[1]));

    // Sani Huttunen 1 7/9 correct.
    Console.WriteLine("Sani Huttunen 1: " + (Regex.Replace(input[0], @"([a-z]?)[_ ]?([A-Z])", "$1 $2").TrimStart(' ') == input[1]));

    // Sani Huttunen 2 9/9 correct.
    Console.WriteLine("Sani Huttunen 2: " + (Regex.Replace(input[0].Replace('_', ' '), @"(?<!^)[ ]?([A-Z])", " $1").TrimStart(' ') == input[1]));

    Console.WriteLine();
  }
}

      

+1


source


For input type: ThisIsAnInputString

        string input1 = "ThisIsAnInputString";
        StringBuilder builder = new StringBuilder();

        foreach (char c in input1)
        {
            if (Char.IsUpper(c))
            {
                builder.Append(' ');
                builder.Append(c);
            }
            else
            {
                builder.Append(c);
            }
        }

        string output = builder.ToString().Trim();

      

For input type: This_Is_An_Input_String

string input2 = "This_Is_An_Input_String";
string output = Regex.Replace(input2, "_([A-Z])", " $1");

      

0


source


    // check if string is empty
        if (string.IsNullOrEmpty(input))
            return string.Empty;


        if (input.Contains('_'))
        {
            return input.Replace('_', ' ');
        }
        else
        {
            StringBuilder newString = new StringBuilder();
            foreach (Char char1 in input)
            {
                if (char.IsUpper(char1))
                    newString.Append(new char[] { ' ', char1 });
                else
                    newString.Append(char1);
            }

            newString.Remove(0, 1);
            return newString.ToString();
        }

      

0


source


    static void Main(string[] args)
    {
        String str = "ThisIsAnInputString";
        String str2 = "This_Is_An_Input_String";

        Console.WriteLine(str);
        Console.WriteLine(str2);

        StringBuilder sb = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();

        str.ToCharArray().ToList().ForEach(c => sb.Append(c == '_' ? " " :  char.IsLower(c) ? c.ToString() : " " + c.ToString()));
        str2.ToCharArray().ToList().ForEach(c => sb2.Append(c == '_' ? " " : char.IsLower(c) ? c.ToString() : " " + c.ToString()));

        str = sb.ToString().Trim(" ".ToCharArray());
        str2 = sb2.ToString().Trim(" ".ToCharArray());

        Console.WriteLine(str);
        Console.WriteLine(str2);



        Console.Read();
    }

      

0


source


Emphasizes:

string inputString = "This_Is_An_Input_String";
string resultString = inputString.Replace('_', ' ');

      

Capital:

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");

      

0


source







All Articles