import java.io.UnsupportedEncodingException;
public class StringTest {
/**
* 判断是否是一个中文汉字
*
* @param c
* 字符
* @return true表示是中文汉字,false表示是英文字母
* @throws UnsupportedEncodingException
* 使用了JAVA不支持的编码格式
*/
public static boolean isChineseChar(char c)
throws UnsupportedEncodingException {
// 如果字节数大于1,是汉字
// 以这种方式区别英文字母和中文汉字并不是十分严谨,但在这个题目中,这样判断已经足够了
return String.valueOf(c).getBytes("UTF-8").length > 1;
}
/**
* 判断传进来的字符串,是否
* 大于指定的字节,如果大于递归调用
* 直到小于指定字节数
* @param s
* 原始字符串
* @param num
* 传进来指定字节数
* @return String 截取后的字符串
*/
public static String idgui(String s,int num){
int changdu = s.getBytes().length;
if(changdu > num){
s = s.substring(0, s.length() - 1);
s = idgui(s,num);
}
return s;
}
public static void main(String[] args) throws Exception{
// 原始字符串
String s = "办公室(董";
System.out.println("原始字符串:" + s + " : 字节数是: " + s.getBytes().length);
System.out.println("截取前12字节:" + idgui(s, 8));
}
}
按字节截取字符串
最新推荐文章于 2023-12-19 09:26:47 发布