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

时间:2011-12-07 13:26:21

标签: c#

我的变量包含如下文字:

ShowSummary
ShowDetails
AccountDetails

C#中有一个简单的方法函数/方法可以应用于这些变量以产生:

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

我想知道一种扩展方法,但我从未编写过一种方法,我不确定从哪里开始。

4 个答案:

答案 0 :(得分:7)

Jon Galloway查看postPhil

查看

答案 1 :(得分:2)

最好的方法是迭代字符串中的每个字符。检查字符是否为大写。如果是这样,请在其前面插入空格字符。否则,请转到下一个字符。

另外,理想情况下从第二个字符开始,以便在第一个字符之前不插入空格。

答案 2 :(得分:1)

在我目前正在处理的应用程序中,我们有一个基于委托的拆分扩展方法。它看起来像这样:

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

然后可以按如下方式使用:

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

这允许您在两个char之间拆分任何条件,并插入您选择的填充(默认空格)。

答案 3 :(得分:1)

尝试这样的事情

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