package mytestfile;
/**
* 写一个方法 String left(String str ,int n) <br>
* str字符串中可能包含中文,中文是2bytes,实现的功能是<br>
* 如:“中abc12” n=4 则该方法返回“中ab”<br>
* “中abc国a” n=6 则返回“中abc”<br>
* 中文是一半时不返回
*
* @author Fee Share
*/
public class LanIP {
public static void main(String[] args) {
String s = "我是acf中d国人adfgdd123";
for (int i = 0; i <= s.getBytes().length; i++) { //23
System.out.printf("%2d=%s\n", i, getSubString(s, i));
}
}
private static String getSubString(String s, int n) {
int count = 0;
int offset = 0;
char[] c = s.toCharArray(); //18
for (int i = 0; i < c.length; i++) {
if (c[i] > 256) {
offset = 2; //偏移量 offset=2
count += 2; // count =2
} else {
offset = 1;
count++;
}
if (count == n) {
return s.substring(0, i + 1);
}
if ((count == n + 1 && offset == 2)) {
return s.substring(0, i);
}
}
return "";
}
}
/**
* 写一个方法 String left(String str ,int n) <br>
* str字符串中可能包含中文,中文是2bytes,实现的功能是<br>
* 如:“中abc12” n=4 则该方法返回“中ab”<br>
* “中abc国a” n=6 则返回“中abc”<br>
* 中文是一半时不返回
*
* @author Fee Share
*/
public class LanIP {
public static void main(String[] args) {
String s = "我是acf中d国人adfgdd123";
for (int i = 0; i <= s.getBytes().length; i++) { //23
System.out.printf("%2d=%s\n", i, getSubString(s, i));
}
}
private static String getSubString(String s, int n) {
int count = 0;
int offset = 0;
char[] c = s.toCharArray(); //18
for (int i = 0; i < c.length; i++) {
if (c[i] > 256) {
offset = 2; //偏移量 offset=2
count += 2; // count =2
} else {
offset = 1;
count++;
}
if (count == n) {
return s.substring(0, i + 1);
}
if ((count == n + 1 && offset == 2)) {
return s.substring(0, i);
}
}
return "";
}
}