字符串中大写的百分比

本文关键字:百分比 字符串 | 更新日期: 2023-09-27 18:35:55

好吧,所以我正在尝试获取字符串中大写字母的百分比。但是,我没有太多运气,因为我当前的代码只说如果 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

字符串中大写的百分比

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

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

或者你可以让 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并且从未转换为double/float/decimal。请注意,您将它除以string.Length这也是一个int

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