zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    MySQL常用函数
    SQL之join
    java并发编程之三--CyclicBarrier的使用
    java并发编程之二--CountDownLatch的使用
    java并发编程之一--Semaphore的使用
    微信小程序 bindcontroltap 绑定 没生效
    报错:Syntax error on tokens, delete these tokens
    java创建类的5种方式
    数据类型转换
    JS数据结构算法---数组的算法
  • 原文地址:https://www.cnblogs.com/weyine/p/7613579.html
Copyright © 2011-2022 走看看