获取字符串中的数字、符号、中文、英文单词、字母、空格、字节、其他字符的个数
2014-09-16 23:55
603 查看
获取字符串中的数字、符号、中文、英文单词、字母、空格、字节、其他字符的个数
转载▼
标签:
| 分类: java |
private static int GetWordCountByRegular(string str)
{
//统计英文单词个数
Regex re = new Regex(@"\b\w+\b");
MatchCollection ma = re.Matches(str);
return ma.Count;
}
//数字
public static int GetNumberCount(string str)
{
int count = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] != '\0')
{
if (str[i] >= '0' && str[i] <= '9')
{
count++;
}
}
}
return count;
}
//字母
public static int GetLetterCount(string str)
{
int count = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] != '\0')
{
if (((str[i] >= 'a' && str[i] <= 'z')) || ((str[i] >= 'A' && str[i] <= 'Z')))
{
count++;
}
}
}
return count;
}
//中文字符
public static int GetChineseCount(String str)
{
//中文个数=字节数-字符数
return Encoding.GetEncoding("gb2312").GetBytes(str).Length - str.Length;
}
//中文字符:根据Unicode编码范围
private static int GetChineseCountByUnicode(string str)
{
int count = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] >= 0X4e00 && str[i] <= 0X9fa5)
{
count++;
}
}
return count;
}
//中文字符:根据正则获取
private static int GetChineseCountByRegular(String str)
{
Regex re = new Regex("[\u4e00-\u9fa5]");
MatchCollection ma = re.Matches(str);
return ma.Count;
}
//空格
public static int GetSpaceCount(String str)
{
int count = 0;
foreach (char ch in str)
{
if (ch == 32) //ASCII编码:32为空格符.当然你也可以判断空字符:ch==' '
{
count++;
}
}
return count;
}
//标点符号
public static int GetSymbolCount(String str)
{
//ASCII编码中的符号范围:32-47、58-64、91-96、123-126
int count = 0;
foreach (char ch in str)
{
if ((ch >= 32 && ch <= 47) || (ch >= 58 && ch <= 64) || (ch >= 91 && ch <= 96) || (ch >= 123 && ch <= 126))
{
count++;
}
}
return count;
}
//其他字符
public static int GetOtherCount(String str)
{
return str.Length - GetNumberCount(str) - GetLetterCount(str) - GetChineseCount(str)
- GetSpaceCount(str) - GetSymbolCount(str);
}
//字节
public static int GetByteCount(String str)
{
return Encoding.Default.GetBytes(str).Length;
}
相关文章推荐
- 获取包含中文,字母,数字集合的字符串的长度(1个汉字字符存储需要2个字节,1个英文字符存储需要1个字节)
- 编写一个函数,分别统计出传入字符串参数(可能不止一个参数)的英文字母,空格,数字和其他字符的个数
- 有一个字符串,其中包含中文字符、英文字符和数字、空格及其他字符,请统计和打印出各个字符的个数。
- 统计传入字符串参数(可能不止一个参数)的英文字母、空格、数字和其他字符的个数
- 输入一个字符串,分别统计出包含的英文字母、数字、空格和其他字符的个数
- 作业三-3输入 15 个字符,统计其中英文字母、空格或回车、数字字符和其他字符的个数
- 作业3-3 输入 15 个字符,统计其中英文字母、空格或回车、数字字符和其他字符的个数
- 输入一行字符,分别统计出其中英文字母 空格 数字和其他字符的个数
- 作业3-3 输入 15 个字符,统计其中英文字母、空格或回车、数字字符和其他字符的个数
- C++练习之 统计英文字母,空格,数字和其他字符的个数
- 用Java统计字符串中的字母、数字、空格和其他字符
- 输入一行字符,分别统计出其中的英文字母,空格,数字和其他字符的个数
- 输入一行字符,分别统计出其中英文字母,空格,数字和其他字符的个数
- c - 统计字符串"字母,空格,数字,其他字符"的个数和行数.
- 关于计算一个字符串中的,数字,字母,空格,其他字符个数说说明
- 作业3(3)输入 15 个字符,统计其中英文字母、空格或回车、数字字符和其他字符的个数
- 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
- 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
- 输入一行字符,分别统计出其中的英文字母、空格、数字、和其他字符的个数
- 求字符串中英文字母,空格,数字,还有其他字符的个数