用.net语言实现统计字母数字空格和其它字符的个数
时间: 2023-11-07 17:05:14 浏览: 39
你可以使用以下代码实现:
```csharp
string str = "Hello World! 123";
int letters = 0;
int digits = 0;
int spaces = 0;
int others = 0;
foreach (char c in str)
{
if (Char.IsLetter(c))
{
letters++;
}
else if (Char.IsDigit(c))
{
digits++;
}
else if (Char.IsWhiteSpace(c))
{
spaces++;
}
else
{
others++;
}
}
Console.WriteLine("Letters: " + letters);
Console.WriteLine("Digits: " + digits);
Console.WriteLine("Spaces: " + spaces);
Console.WriteLine("Others: " + others);
```
这个代码会输出:
```
Letters: 10
Digits: 3
Spaces: 3
Others: 2
```
其中,`Char.IsLetter(c)`、`Char.IsDigit(c)` 和 `Char.IsWhiteSpace(c)` 是 .NET 中的字符判断函数,分别用于判断字符是否为字母、数字和空格。