Java逻辑代码判断字数

package com.wyl.test;
public class WorldTrueCount {
/**
* 判断中文和标点符号的逻辑代码

*对应规则:中文一对一,英语单词一对一,标点符号一对一,空格回车不算
* @param value
* @return
*/
public static int String_length_chinese(String value) {
 int valueLength = 0;
 String chinese = "[\u4e00-\u9fa5]";
 String english = "[a-zA-Z]";
 for (int i = 0; i < value.length(); i++) {
  String temp = value.substring(i, i + 1);
  if(temp.equals(" ")){
   valueLength+=0;
  }else if (temp.matches(chinese)) {
   valueLength += 1;
  }else if(temp.matches(english)) {
   valueLength += 0;
  }else{
   valueLength += 1;
  }
 }
 return valueLength;
}
/**
* 判断英文的逻辑代码
* @param value
* @return
*/
public static int String_length_english(String value) {
 int valueLength = 0;
 String chinese = "[\u4e00-\u9fa5]";
 String english = "[a-zA-Z]";
 int k=0;
 for (int i = 0; i < value.length(); i++) {
  String temp = value.substring(i, i + 1);
  if(temp.equals(" ")){
   if(k==1){
    valueLength+=1;
    k=0;
   }
  valueLength+=0;
  }else if (temp.matches(chinese)) {
   if(k==1){
    valueLength+=1;
    k=0;
  }
  valueLength += 0;
  }else if(temp.matches(english)) {
   if(i==value.length()-1){//循环到最后一位是字母时长度也要加1
    valueLength += 1;
   }
   k = 1;
   valueLength += 0;
  }else{
   if(k==1){
    valueLength+=1;
    k=0;
  }
  valueLength += 0;//标点符号
  }
 }
 return valueLength;
}


}

下面是本人写的一个简单的测试例子,很好使

package com.wyl.test;

public class Test {
 public static void main(String[] args) {
  String value="ss我的  w你o,d哈哈e s啦s";
  int length_chinese=WorldTrueCount.String_length_chinese(value);
  int length_english=WorldTrueCount.String_length_english(value); 
  System.out.println("中文和标点/"+length_chinese+"\n"+"英语单词/"+length_english);
  System.out.println("一共:"+(length_chinese+length_english));
  
 }
}

//下面是控制台的输出

中文和标点/7
英语单词/7
一共:14

 

posted @ 2017-09-30 08:44  亮亮的繁星相随  阅读(1448)  评论(0编辑  收藏  举报