在小写和大写之间添加间距

本文关键字:添加 之间 | 更新日期: 2023-09-27 17:59:53

当字符串中有大写字符或下划线时,我想添加一个空格。

我该怎么做?

示例1

输入

ThisIsAnInputString

输出(结果)

This Is An Input String

示例2

输入

This_Is_An_Input_String

输出(结果)

This Is An Input String

在小写和大写之间添加间距

您可以使用一个正则表达式,该表达式匹配一个小写字符和一个大写字符,并在以下字符之间添加可选下划线:

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

你可能还想用它来处理单个字符的单词:

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

下划线:

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

资本:

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

根据您的规范,您希望在任何大写字符之前添加一个空格。这也应该适用于第一个字母。所有下划线都应替换为空格。这里的大多数答案省略了第一个空格(在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"

如果您不想在开始时使用额外的空间,请使用TrimStart

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

编辑(更新):

我已经将不同的regex建议编译到一个小型测试应用程序中以验证结果:

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();
  }
}

对于输入类型: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();

输入类型:This_Is_An_Input_String

string input2 = "This_Is_An_Input_String";
string output = Regex.Replace(input2, "_([A-Z])", " $1");
    // 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();
        }
    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();
    }