判断字符长度
Posted MIC2016
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了判断字符长度相关的知识,希望对你有一定的参考价值。
/** * 判断姓名字符长度 * 字符串为空返回0;有中文返回中文字符数;无中文返回2 * @param CustomerSn * @return */ private Integer getNameLength(Integer CustomerSn){ Integer sealWidth = 32; CustomerDto customerDto = customerService.getCustomerBySnForEsign(CustomerSn); String custSurname = customerDto.getCustSurname(); String custName = customerDto.getCustName(); Integer SurnameLen = this.count(custSurname); Integer NameLen = this.count(custName); Integer length = SurnameLen+NameLen; if(length>=0 && length<=4){ sealWidth = length*16; }else if(length.equals(5) ||length.equals(6)){ sealWidth = 3*16; } return sealWidth; } /*** * 统计字符串中中文,英文,数字,空格等字符个数 * @param str 需要统计的字符串 */ private Integer count(String str) { int chCharacter = 0;//中文字符 int enCharacter = 0;//英文字符 int spaceCharacter = 0;//空格 int numberCharacter = 0;//数字 int otherCharacter = 0;//其他字符 if (null == str || str.equals("")) { return 0; } for (int i = 0; i < str.length(); i++) { char tmp = str.charAt(i); if ((tmp >= ‘A‘ && tmp <= ‘Z‘) || (tmp >= ‘a‘ && tmp <= ‘z‘)) { enCharacter ++; } else if ((tmp >= ‘0‘) && (tmp <= ‘9‘)) { numberCharacter ++; } else if (tmp ==‘ ‘) { spaceCharacter ++; } else if (isChinese(tmp)) { chCharacter ++; } else { otherCharacter ++; } } logger.info("字符串:" + str + " "+"中文字符有:" + chCharacter+"英文字符有:" + enCharacter+"数字有:" + numberCharacter+"空格有:" + spaceCharacter+"其他字符有:" + otherCharacter); if(chCharacter>0){ return chCharacter; }else{ return 1; } } private boolean isChinese(char ch) { //获取此字符的UniCodeBlock Character.UnicodeBlock ub = Character.UnicodeBlock.of(ch); // GENERAL_PUNCTUATION 判断中文的“号 // CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号 // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号 if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) { return true; } return false; }
以上是关于判断字符长度的主要内容,如果未能解决你的问题,请参考以下文章