??? 翻了翻以前積累下的一些資料,看到其中有一個統計中英文字符數的例子,很簡單,感覺也比較有意思,一直以來都沒有這么去想過問題,現在把它記下來。
import
?java.io.
*
;


public
?
class
?Test?
{

????
/**?*/
/**
?????*?統計字串中中文字符數量
?????*?
@param
?str:GB編碼字符串
?????
*/
????
public
?
static
?
int
?statGBCharCount1(String?str)?
{
????????
int
?GBCount?
=
?
-
1
;
????????String?otherStr?
=
?
null
;
????????

????????
try
{
????????????otherStr?
=
?
new
?String(str.getBytes(),
"
ISO8859_1
"
);
????????????GBCount?
=
?otherStr.length()?
-
?str.length();

????????}
catch
(UnsupportedEncodingException?ex)
{
????????????
throw
?
new
?RuntimeException(
"
UnsupportedEncodingException
"
);
????????}
????????
????????
return
?GBCount;
????}
????
/**?*/
/**
?????*?統計字串中中文字符數量
?????
*/
????
public
?
static
?
int
?statGBCharCount2(String?str)?
{
????????
int
?GBCount?
=
?
-
1
;
????????
????????GBCount?
=
?str.replaceAll(
"
[\u0000-\u0127]
"
,
""
).length();
????????System.out.println(
"
asc字符:
"
?
+
?str.replaceAll(
"
[\u0000-\u0127]
"
,
""
));
????????System.out.println(
"
非asc字符:
"
?
+
?str.replaceAll(
"
[^\u0000-\u0127]
"
,
""
));
????????
????????
return
?GBCount;
????}
????

????
public
?
static
?
void
?main(String[]?args)?
{
????????String?str?
=
?
"
This?is?test?string?這是一個測試字符串
"
;
????????System.out.println(
"
中文字符數:
"
+
?Test.statGBCharCount1(str));
????????System.out.println(
"
中文字符數:
"
+
?Test.statGBCharCount2(str));
????}
}
可以看到,方法1中使用的辦法,可能局限性更大,不過也是一種思路。
自己想的是第2種方法,用正則表達式直接過濾,也挺快捷。























































可以看到,方法1中使用的辦法,可能局限性更大,不過也是一種思路。
自己想的是第2種方法,用正則表達式直接過濾,也挺快捷。