简体   繁体   English

如何将PascalCase转换为拆分单词?

[英]How can I convert PascalCase to split words?

I have variables containing text such as: 我有包含文本的变量,例如:

ShowSummary
ShowDetails
AccountDetails

Is there a simple way function / method in C# that I can apply to these variables to yield: 在C#中有一个简单的方法函数/方法,我可以应用于这些变量来产生:

"Show Summary"
"Show Details"
"Account Details"

I was wondering about an extension method but I've never coded one and I am not sure where to start. 我想知道一个扩展方法,但我从来没有编写过一个,我不知道从哪里开始。

请看Jon Galloway撰写的这篇文章Phil的一篇文章

The best would be to iterate through each character within the string. 最好的方法是迭代字符串中的每个字符。 Check if the character is upper case. 检查字符是否为大写。 If so, insert a space character before it. 如果是这样,请在其前面插入空格字符。 Otherwise, move onto the next character. 否则,转到下一个字符。

Also, ideally start from the second character so that a space would not be inserted before the first character. 另外,理想情况下从第二个字符开始,以便在第一个字符之前不插入空格。

In the application I am currently working on, we have a delegate based split extension method. 在我目前正在处理的应用程序中,我们有一个基于委托的拆分扩展方法。 It looks like so: 它看起来像这样:

public static string Split(this string target, Func<char, char, bool> shouldSplit, string splitFiller = " ")
{
    if (target == null)
        throw new ArgumentNullException("target");

    if (shouldSplit == null)
        throw new ArgumentNullException("shouldSplit");

    if (String.IsNullOrEmpty(splitFiller))
        throw new ArgumentNullException("splitFiller");

    int targetLength = target.Length;

    // We know the resulting string is going to be atleast the length of target
    StringBuilder result = new StringBuilder(targetLength);

    result.Append(target[0]);

    // Loop from the second character to the last character.
    for (int i = 1; i < targetLength; ++i)
    {
        char firstChar = target[i - 1];
        char secondChar = target[i];

        if (shouldSplit(firstChar, secondChar))
        {
            // If a split should be performed add in the filler
            result.Append(splitFiller);
        }

        result.Append(secondChar);
    }

    return result.ToString();
}

Then it is could be used as follows: 然后可以使用如下:

string showSummary = "ShowSummary";
string spacedString = showSummary.Split((c1, c2) => Char.IsLower(c1) && Char.IsUpper(c2));

This allows you to split on any conditions between two char s, and insert a filler of your choice (default of a space). 这允许您在两个char之间拆分任何条件,并插入您选择的填充(默认空格)。

try something like this 尝试这样的事情

var word = "AccountDetails";
word = string.Join(string.Empty,word
    .Select(c => new string(c, 1)).Select(c => c[0] < 'Z' ? " " + c : c)).Trim();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM