Java写一个判断字符长度的方法,全是中文字符时,一个中文字符占3个字节,上限为32字节。包含英文字符的或全英文字符一个英文字符1字节,一个中文字符3字节,总长度24字节
时间: 2024-03-21 09:41:48 浏览: 22
可以使用 Java 的正则表达式和字符编码来实现判断字符长度的方法,示例代码如下:
```java
public static int getLength(String str) {
int len = 0;
// 匹配中文字符
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
len += 3; // 中文字符长度为3
}
// 匹配非中文字符
len += str.replaceAll(regEx, " ").getBytes(StandardCharsets.UTF_8).length; // 非中文字符长度为1
// 判断是否包含英文字符
if (str.matches(".*[a-zA-Z]+.*")) {
len = Math.min(len, 24); // 包含英文字符,总长度不能超过24个字节
} else {
len = Math.min(len, 32); // 全中文字符,总长度不能超过32个字节
}
return len;
}
```
使用该方法可以判断字符串的长度是否符合要求,例如:
```java
String str1 = "这是一个中文字符串";
int len1 = getLength(str1); // 30
String str2 = "This is an English string";
int len2 = getLength(str2); // 24
String str3 = "这是一个非常长的中文字符串,超过了上限";
int len3 = getLength(str3); // 32
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)