Java 計算中英文長度的若干種方法,java計算中英文長度
在項目開發中經常碰到到輸入字元的校正,特別是中英文混合在一起的校正。而為了滿足校正的需求,有時需要計算出中英文的長度。
本文將通過幾種常用的方法實現長度的計算:
<span style="font-size:18px;">import java.io.UnsupportedEncodingException;/** * 中英文校正的處理 * @author a123demi * */public class EnChValidate {public static void main(String[] args){String validateStr= "中英文校正abcde介面ii";int bytesStrLength = getBytesStrLength(validateStr);int chineseLength = getChineseLength(validateStr);int regexpLength = getRegExpLength(validateStr);System.out.println("getBytesLength:" + bytesStrLength + ",chineseLength:" + chineseLength + ",regexpLength:" + regexpLength);}/** * 根據字元編碼 位元組數產生一個臨時的字串 * @param validateStr * @return */public static int getBytesStrLength(String validateStr){String tempStr = "";try {tempStr = new String(validateStr.getBytes("gb2312"),"iso-8859-1");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}return tempStr.length();}/** * 擷取字串的長度,如果有中文,則每個中文字元計為2位 * * @param validateStr * 指定的字串 * @return 字串的長度 */ public static int getChineseLength(String validateStr) { int valueLength = 0; String chinese = "[\u0391-\uFFE5]"; /* 擷取欄位值的長度,如果含中文字元,則每個中文字元長度為2,否則為1 */ for (int i = 0; i < validateStr.length(); i++) { /* 擷取一個字元 */ String temp = validateStr.substring(i, i + 1); /* 判斷是否為中文字元 */ if (temp.matches(chinese)) { /* 中文字元長度為2 */ valueLength += 2; } else { /* 其他字元長度為1 */ valueLength += 1; } } return valueLength; } /** * 利用Regex將每個中文字元轉換為"**" * 匹配中文字元的Regex: [\u4e00-\u9fa5] * 匹配雙位元組字元(包括漢字在內):[^\x00-\xff] * @param validateStr * @return */ public static int getRegExpLength(String validateStr){// String temp = validateStr.replaceAll("[\u4e00-\u9fa5]", "**"); String temp = validateStr.replaceAll("[^\\x00-\\xff]", "**"); return temp.length(); }}</span>
java中 怎計算中英文字串混合的長度
import java.io.*;
public class StringTest
{
public static void main(String[] args)
{
String aString = ="你好,abc";
String anotherString = null;
try {
anotherString = new String(aString.getBytes("GBK"), "ISO8859_1");
}
catch (UnsupportedEncodingException ex) {
}
System.out.println(aString.length() + "," + anotherString.length());
}
}
簡單的JAVA字串長度計算的實現
剛編的 還有什麼不懂的就問我
import java.util.Scanner;
public class ZiFuChuanChangDuTest {
public int f1(String a){
int sum=0;
sum=a.length();
return sum;
}
public static void main(String args[]){
ZiFuChuanChangDuTest n=null;
n=new ZiFuChuanChangDuTest();
Scanner sc=new Scanner(System.in);
System.out.println("請輸入字元:");
String i=sc.nextLine();
System.out.println("字串長度為:"+n.f1(i));
}
}