C# string.split() separate string by uppercase

眉间皱痕 提交于 2020-11-26 06:19:41

问题


I've been using the Split() method to split strings. But this work if you set some character for condition in string.Split(). Is there any way to split a string when is see Uppercase?

Is it possible to get few words from some not separated string like:

DeleteSensorFromTemplate

And the result string is to be like:

Delete Sensor From Template

回答1:


Use Regex.split

string[] split =  Regex.Split(str, @"(?<!^)(?=[A-Z])");



回答2:


If you do not like RegEx and you really just want to insert the missing spaces, this will do the job too:

public static string InsertSpaceBeforeUpperCase(this string str)
{   
    var sb = new StringBuilder();

    char previousChar = char.MinValue; // Unicode '\0'

    foreach (char c in str)
    {
        if (char.IsUpper(c))
        {
            // If not the first character and previous character is not a space, insert a space before uppercase

            if (sb.Length != 0 && previousChar != ' ')
            {
                sb.Append(' ');
            }           
        }

        sb.Append(c);

        previousChar = c;
    }

    return sb.ToString();
}



回答3:


Another way with regex:

public static string SplitCamelCase(string input)
{
   return System.Text.RegularExpressions.Regex.Replace(input, "([A-Z])", " $1", System.Text.RegularExpressions.RegexOptions.Compiled).Trim();
}


来源:https://stackoverflow.com/questions/36147162/c-sharp-string-split-separate-string-by-uppercase

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!