中文占一个字符啊我晕,怎么会拆开呢刚才上面的结果是t e s t 中 d 文 d s a f 中 男 大 3 4 4 3 n 中 国 4 3 中 国 人 0 e w l d f l s = 1 0 3 你试试就知道了
List<String> list = new ArrayList<String>(); String s = "test中d文dsaf中男大3443n中国43中国人0ewldfls=103"; for (int i = 1; i < s.length(); i++) { if (i == s.length() - 1) list.add(s.substring(i - i % 4)); else if (i % 4 == 0) list.add(s.substring(i - 4, i)); } System.out.println(list); 每4个字符分开
for example String s = "test中d文dsaf中男大3443n中国43中国人0ewldfls=103"; List<String> list = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); for (char c : s.toCharArray()) { if (buf.toString().getBytes().length + Character.toString(c).getBytes().length > 4) { list.add(buf.toString()); buf.delete(0, buf.length()); } buf.append(c); } System.out.println(list);
还是直接用字符判断吧,其实和上面的代码差不多,不过感觉这样效率好一些 String s = "test中d文dsaf中男大3443n中国43中国人0ewldfls=103"; List<String> list = new ArrayList<String>(); StringBuilder buf = new StringBuilder(); int count = 0; for (char c : s.toCharArray()) { count += (c>=0x4e00 && c<=0x9fa5) ? 2 : 1; if (count > 4) { list.add(buf.toString()); buf.delete(0, buf.length()); count = (c>=0x4e00 && c<=0x9fa5) ? 2 : 1; } buf.append(c);
} if (buf.length() > 0) {list.add(buf.toString());} System.out.println(list);
中d 属于四个字符吗?
文ds 属于四个字符?
但 中d 文ds 字符数不同呀
out
test
中d文d
saf中
……
public class SplitStringWithZH { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "test中d文dsaf中男大3443n中国43中国人0ewldfls=103";
char[] dstChar = s.toCharArray();
s.getChars(0, s.length(), dstChar, 0);
for (int j = 0; j < dstChar.length; j++)
{
System.out.print(dstChar[j]+ "\t");
}
}
}
楼主是否认为一个汉字算两个字符?这是native编码中的老观念了java中使用unicode,'a'和'中'一样长,都是一个字符
String s = "test中d文dsaf中男大3443n中国43中国人0ewldfls=103";
for (int i = 1; i < s.length(); i++) {
if (i == s.length() - 1)
list.add(s.substring(i - i % 4));
else if (i % 4 == 0)
list.add(s.substring(i - 4, i));
}
System.out.println(list);
每4个字符分开
String s = "test中d文dsaf中男大3443n中国43中国人0ewldfls=103";
List<String> list = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
for (char c : s.toCharArray()) {
if (buf.toString().getBytes().length + Character.toString(c).getBytes().length > 4) {
list.add(buf.toString());
buf.delete(0, buf.length());
}
buf.append(c);
}
System.out.println(list);
String s = "test中d文dsaf中男大3443n中国43中国人0ewldfls=103";
List<String> list = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
int count = 0;
for (char c : s.toCharArray()) {
count += (c>=0x4e00 && c<=0x9fa5) ? 2 : 1;
if (count > 4) {
list.add(buf.toString());
buf.delete(0, buf.length());
count = (c>=0x4e00 && c<=0x9fa5) ? 2 : 1;
}
buf.append(c);
}
if (buf.length() > 0) {list.add(buf.toString());}
System.out.println(list);