自定义功能的大写字符分割字符串不按预期工作 [英] Custom function for splitting string on Upper Case characters does not works as expected
本文介绍了自定义功能的大写字符分割字符串不按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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]);
}
这篇关于自定义功能的大写字符分割字符串不按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文