public
class
stringlength
{
/**
*
*
@param
value
指定的字符串
*
@return
字符串的长度
*/
public
static
int
length(string
value)
{
int
valuelength
=
0
string
chinese
=
"[\u0391-\uffe5]"
/*
获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
*/
for
(int
i
=
0
i
<
value.length()
i++)
{
/*
获取一个字符
*/
string
temp
=
value.substring(i,
i
+
1)
/*
判断是否为中文字符
*/
if
(temp.matches(chinese))
{
/*
中文字符长度为2
*/
valuelength
+=
2
}
else
{
/*
其他字符长度为1
*/
valuelength
+=
1
}
}
return
valuelength
}
public
static
void
main(string
args[]){
string
str
=
"hello你好"
system.out.println(stringlength.length(str))
}
}
字符串是length().数组才是字符串的length属性.这个东西有个问题.无论是汉字,符号,还是字母都会输出长度.
我这个不仅可以统计汉字数量,而且可以提取出汉字.
import java.util.regex.Matcher
import java.util.regex.Pattern
public class Test {
public static void main(String[] args) {
int count = 0
String regex = "[\u4e00-\u9fa5]"
String str = "今天阳光明媚zh2345678{不是吗},是的."
Pattern p = Pattern.compile(regex)
Matcher m = p.matcher(str)
System.out.print("提取出来的中文有:")
while (m.find()) {
count++
System.out.print(m.group() + " ")
}
System.out.println()
System.out.println("汉字出现的频率:" + count)
}
}