Java中的字符串截取
编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
这是我面试时候遇到的问题,刚开始的时候,思维就陷入了定势:用String的getBytes()方法将字符串转化为byte数组,然后在遍历数组,每次遍历的时候要判断当前字符是字母还是汉字,面试的时候想着用正则判断汉字,却忘了正则表达式是怎样的。结果思路对了,就差不知道判断中文的正则怎样写了!
现在,想了想怎样实现上门的要求。找到实现的方法如下:
package stringTest;
import java.io.UnsupportedEncodingException;
public class SplitString {
/**
* 按字节截取字符串
*
* @param orignal
* 原始字符串
* @param count
* 截取位数
* @return 截取后的字符串
* @throws UnsupportedEncodingException
* 使用了JAVA不支持的编码格式
*/
public String substring(String orignal, int count)
throws UnsupportedEncodingException {
// 原始字符不为null,也不是空字符串
if (orignal != null && !”".equals(orignal)) {
// 将原始字符串转换为GBK编码格式
orignal = new String(orignal.getBytes(), “GBK”);
// 要截取的字节数大于0,且小于原始字符串的字节数
if (count > 0 && count < orignal.getBytes(“GBK”).length) {
StringBuffer buff = new StringBuffer();
char c;
for (int i = 0; i < count; i++) {
// charAt(int index)也是按照字符来分解字符串的
c = orignal.charAt(i);
buff.append(c);
if (isChineseChar(c)) {
// 遇到中文汉字,截取字节总数减1
–count;
}
}
return buff.toString();
}
}
return orignal;
}
/**
* 判断是否是一个中文汉字
*
* @param c
* 字符
* @return true表示是中文汉字,false表示是英文字母
* @throws UnsupportedEncodingException
* 使用了JAVA不支持的编码格式
*/
public boolean isChineseChar(char c) throws UnsupportedEncodingException {
// 如果字节数大于1,是汉字
// 以这种方式区别英文字母和中文汉字并不是十分严谨,但在这个题目中,这样判断已经足够了
return String.valueOf(c).getBytes(“GBK”).length > 1;
}
public static void main(String[] args) {
String st = “test中dd文dsaf中男大3443n中国43中国人0ewldfls=103″;
SplitString ss = new SplitString();
try {
System.out.println(“使用重写的subString截取:”+ss.substring(st, 5));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
这里区别英文字母和中文汉字并不是十分严谨,使用的方法是:
return String.valueOf(c).getBytes(“GBK”).length > 1;
当然,还有其他的办法可以判别。这只u是解决办法之一,后来看了看String的其他方法,发现还有一种更简单的解决办法:
package stringTest;
import java.io.UnsupportedEncodingException;
public class SplitString {
String SplitStr;
int SplitByte;
public SplitString(String str, int bytes) {
SplitStr = str;
SplitByte = bytes;
System.out.println(“The String is:’” + SplitStr + “‘;SplitBytes=”
+ SplitByte + “;The String length:” + SplitStr.length());
}
public void SplitIt() {
int loopCount;
loopCount = (SplitStr.length() % SplitByte == 0)
? (SplitStr.length() / SplitByte)
: (SplitStr.length() / SplitByte + 1);
System.out.println(“Will Split into ” + loopCount);
for (int i = 1; i <= loopCount; i++) {
if (i == loopCount) {
System.out.println(SplitStr.substring((i – 1) * SplitByte,
SplitStr.length()));
} else {
System.out.println(SplitStr.substring((i – 1) * SplitByte,
(i * SplitByte)));
}
}
}
public static void main(String[] args) {
String st = “test中dd文dsaf中男大3443n中国43中国人0ewldfls=103″;
SplitString ss = new SplitString(st, 4);
ss.SplitIt();
}
}
这种方法使用的是String的subString方法,好处是不用关注当前的字符是字母还是汉字了。

nothing