/**
* 截取字符串,带中文字符的实现
* 关键两点:1:识别中文字符;2:根据截取规则截取字符串
* @author joy
*
*/
public class MySubString {
private String str;
MySubString (String str) {
this.str = str;
}
/**
* 根据Unicode编码判断中文汉字和符号
* @param c
* @return
*
* @see http://www.apihome.cn/api/java/Character.UnicodeBlock.html
*/
private static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
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;
}
public String substring(int start, int end) {
StringBuilder targetStr = new StringBuilder();
char []sourceStr = str.toCharArray();
int len = sourceStr.length;
int i = 0;
char temp;
if (start > end || start > len || end < 0) {
return null;
}
for (int count = 0; count <= end; count++, i++) {
if (count >= start) {
temp = sourceStr[i];
targetStr.append(temp);
if (isChinese(temp)) {
count += 1;
}
}
}
return targetStr.toString();
}
public static void main (String args[]) {
System.out.println(new MySubString("国人abc").substring(1,3));
}
}
* 截取字符串,带中文字符的实现
* 关键两点:1:识别中文字符;2:根据截取规则截取字符串
* @author joy
*
*/
public class MySubString {
private String str;
MySubString (String str) {
this.str = str;
}
/**
* 根据Unicode编码判断中文汉字和符号
* @param c
* @return
*
* @see http://www.apihome.cn/api/java/Character.UnicodeBlock.html
*/
private static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
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;
}
public String substring(int start, int end) {
StringBuilder targetStr = new StringBuilder();
char []sourceStr = str.toCharArray();
int len = sourceStr.length;
int i = 0;
char temp;
if (start > end || start > len || end < 0) {
return null;
}
for (int count = 0; count <= end; count++, i++) {
if (count >= start) {
temp = sourceStr[i];
targetStr.append(temp);
if (isChinese(temp)) {
count += 1;
}
}
}
return targetStr.toString();
}
public static void main (String args[]) {
System.out.println(new MySubString("国人abc").substring(1,3));
}
}