自定义功能的大写字符分割字符串不按预期工作自定义、字符串、不按、字符

2023-09-12 21:23:53 作者:相爱就爱,别怕阻碍

public static string UpperCaseStringSplitter(string stringToSplit)
{
    var stringBuilder = new StringBuilder();
    foreach (char c in stringToSplit)
    {
        if (Char.IsUpper(c) && stringToSplit.IndexOf(c) > 0)
            stringBuilder.Append(" " + c);
        else
            stringBuilder.Append(c);
    }
    return stringBuilder.ToString();
}

如果我传递一个字符串是这样的:

If I pass a string like this:

TestSrak

输出所预期的:测试Srak

但是,当存在两个相同的字母,其中一个是小写而另一个下大写彼此,开口不会发生:

But when there are two same letters where one is lower case and the other is Uppercase next to each other, the split does not happen:

例如如果输入是:

TestTruck

的输出也是 TestTruck 。你能告诉我问题出在哪里,我怎么能解决这个问题。谢谢!

The output is also TestTruck . Can You please tell me where is the problem and how can I fix it. Thanks!

推荐答案

问题是这样的

stringToSplit.IndexOf(c) > 0)

TestTruck的第一个字母(指数== 0)也是 T ,因此它会没有进入如果

In "TestTruck" the first letter(index == 0) is also a T, therefore it will not enter the if.

相反,我会用一个 for循环并检查当前char是第一个,那么你可以跳过拆分:

Instead i would use a for-loop and check if the current char is the first, then you can skip the split:

for(int i=0; i < stringToSplit.Length; i++)
{
    if (i > 0 && Char.IsUpper(stringToSplit[i]))
        stringBuilder.Append(" ").Append(stringToSplit[i]);
    else
        stringBuilder.Append(stringToSplit[i]);
}