字符串中大写字母的百分比

时间:2016-02-24 08:45:45

标签: c# string

好吧,所以我试图在字符串中获得大写字母的百分比。但是,我没有太多运气,因为我当前的代码只是说如果100%的字符串是大写的则打印出来。

int capsCount = 0;
foreach (char c in e.message)
{
    if (Char.IsUpper(c))
        capsCount++;
}

Console.WriteLine($"{(capsCount/e.message.Replace(" ", string.Empty).Length).ToString("0.00%")} is caps.");
Console.WriteLine($"{e.message.Replace(" ", string.Empty).Length}:{capsCount}");

从控制台输出,#sydth是irc通道,sydth是用户名,test是消息。

#sydth:sydth:TEST
100.00% is caps.
4:4

#sydth:sydth:test
0.00% is caps.
4:0

#sydth:sydth:teST
0.00% is caps.
4:2

2 个答案:

答案 0 :(得分:1)

您需要将capsCount分区中的至少一个属性和字符串中的字符数转换为小数,以便将除法视为十进制除法而不是整数除法。

decimal capsCount = 0;
foreach (char c in e.message)
{
    if (Char.IsUpper(c))
        capsCount++;
}

Console.WriteLine($"{(capsCount/e.message.Replace(" ", string.Empty).Length).ToString("0.00%")} is caps.");
Console.WriteLine($"{e.message.Replace(" ", string.Empty).Length}:{capsCount}");

或者你可以使capsCount成为小数而不是int;

{{1}}

答案 1 :(得分:0)

这是因为您的capsCountint且从未投放到double/float/decimal。请注意,您将其除以string.Lengthint也是capsCount/e.message.Replace(" ", string.Empty).Length //both are int

(int)9/(int)20 //illustration 9/20 -> 0.45 -> rounded down to 0

因此,当您将较低值整数除以较高值整数时:

e.message.Length

结果向下舍入,您将始终为零(capsCount始终大于double

最简单的解决方案是首先将其定义为double capsCount; //declare as double

((double)capsCount/e.message.Replace(" ", string.Empty).Length).ToString("0.00%") //note that there is (double) there for casting

或者,只需在操作前先将其双重投射:

# wrong
exec echo abc | tr [a-z] [A-Z]

# good
exec echo abc | tr \[a-z\] \[A-Z\]