[java]代码库
import java.io.UnsupportedEncodingException;
public class CutString {
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "我们DEF";
int n = 5;
String str = cutString(s, n);
System.out.println(str);
}
private static String cutString(String s, int n)
throws UnsupportedEncodingException {
// TODO Auto-generated method stub
if (s != null && "".equals(s)) {
s = new String(s.getBytes(), "GBK");
}
StringBuffer buffer = new StringBuffer();
if (n != 0 && n < s.getBytes("GBK").length) {
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
buffer.append(c);
// System.out.println("buffer=" + buffer.toString());
if (CutString.isChinens(c)) {
--n;
}
}
}
return buffer.toString();
}
private static boolean isChinens(char c)
throws UnsupportedEncodingException {
// TODO Auto-generated method stub
if (String.valueOf(c).getBytes("GBK").length > 1) {
return true;
} else {
return false;
}
}
}