解答如下:package lihan;/** * * * 关于java按字节截取带有汉字的字符串的解法 * @author 李晗 * */public class test{ public void splitIt(String splitStr, int bytes) { int cutLength = 0; int byteNum = bytes; byte bt[] = splitStr.getBytes(); System.out.println("Length of this String ===>" + bt.length); if (bytes > 1) { for (int i = 0; i < byteNum; i++) { if (bt[i] < 0) { cutLength++; } } if (cutLength % 2 == 0) { cutLength /= 2; }else { cutLength=0; } } int result=cutLength+--byteNum; if(result>bytes) { result=bytes; } if (bytes == 1) { if (bt[0] < 0) { result+=2; }else { result+=1; } } String substrx = new String(bt, 0, result); System.out.println(substrx); } public static void main(String args[]) { String str = "我abc的DEFe呀fgsdfg大撒旦"; int num =3; System.out.println("num:" + num); test sptstr = new test(); sptstr.splitIt(str, num); } }
运行结果:num:3 Length of this String ===>25 我a num:2 Length of this String ===>25 我num:1 Length of this String ===>25 我num:4 Length of this String ===>25 我ab
字符为 中文判断方法是遍历byte,当到中文时候byte[i]返回负值
import java.util.ArrayList; import java.util.Iterator; public class Test{ int bytes; ArrayList<String> list =new ArrayList<String>(); public Test(int bytes){ this.bytes=bytes; } public void splitIt(String s){ if(s.getBytes().length<=bytes){ //判断字符串小于指定字节 list.add(s); return ; }
public class Test { private String t7(String str, int num) {//num表示一char进行截取的字符数 String reStr = str.substring(0,num);//substring函数也是以char进行字符的截取 不是以byte截取
if(str.length() == str.getBytes().length) { // } else { int len = str.getBytes().length;//获得字符串的字节
while (len > num){//字节数大于字符数 说明字符串中有汉字 reStr = reStr.substring(0,reStr.length()-1); len = reStr.getBytes().length; } } return reStr; } public static void main(String[]args) { Test z = new Test(); String s = z.t7("我abc汉def",6); System.out.println("result== "+s); } }
*
*
* 关于java按字节截取带有汉字的字符串的解法
* @author 李晗
*
*/public class test{ public void splitIt(String splitStr, int bytes) {
int cutLength = 0;
int byteNum = bytes;
byte bt[] = splitStr.getBytes();
System.out.println("Length of this String ===>" + bt.length);
if (bytes > 1) {
for (int i = 0; i < byteNum; i++) {
if (bt[i] < 0) {
cutLength++; }
} if (cutLength % 2 == 0) {
cutLength /= 2;
}else
{
cutLength=0;
}
}
int result=cutLength+--byteNum;
if(result>bytes)
{
result=bytes;
}
if (bytes == 1) {
if (bt[0] < 0) {
result+=2; }else
{
result+=1;
}
}
String substrx = new String(bt, 0, result);
System.out.println(substrx); } public static void main(String args[]) {
String str = "我abc的DEFe呀fgsdfg大撒旦";
int num =3;
System.out.println("num:" + num);
test sptstr = new test();
sptstr.splitIt(str, num);
} }
Length of this String ===>25
我a
num:2
Length of this String ===>25
我num:1
Length of this String ===>25
我num:4
Length of this String ===>25
我ab
import java.util.Iterator;
public class Test{
int bytes;
ArrayList<String> list =new ArrayList<String>();
public Test(int bytes){
this.bytes=bytes;
} public void splitIt(String s){
if(s.getBytes().length<=bytes){ //判断字符串小于指定字节
list.add(s);
return ;
}
int temp=0;//字节标记
int i=0;//字符串标记 while(temp<bytes){//从字符串第一个字符开始统计,直到字节大于等于指定字节后跳出循环
temp+=(s.charAt(i++)+"").getBytes().length;
}
//System.out.println(temp);
if(temp==bytes){//如果temp刚好等于指定字节,就直接截取字符串
String s1 = s.substring(0,i);
list.add(s1);
splitIt(s.substring(i));//继续截取剩下的
}
else{
String s1 = s.substring(0,i-1);//如果temp大与指定字节,那就表示最后一个是汉字,就退一位截取字符串 list.add(s1);
splitIt(s.substring(i-1));//继续截取剩下的
}
}
public void print(){
System.out.println(list);
}
public static void main(String []args){
Test test1 = new Test(5);
test1.splitIt("dsad在现在是dsadas小");
test1.print();
}
}
我也来一个
答:一个很简单的问题,楼主代码弄得太复杂了.public class TestSplit {
public static String split(String s,int n)
{
int d=n,i=0;
while( i<s.length() && (d>1 || d==1 && s.charAt(i)<256) )
{
if(s.charAt(i)<256) d--;
else d-=2;
i++;
}
return s.substring(0,i);
}
public static void main(String[] args) {
System.out.println(split("我A汉BC字D",4));
System.out.println(split("我A汉BC字D",5));
System.out.println(split("我A汉BC字D",12));
}}程序运行结果:
我A
我A汉
我A汉BC字D
public class test1{
public static void main(String[] args){
int nums=4;
String str="我我bc汉def";
int jishu=0;
byte bytes[]=str.getBytes();
for(int i=0;i<nums;i++){
if(bytes[i]<0){
jishu++;
}
}
if(jishu%2==0){//如果有偶数个汉字
String str1=new String(bytes,0,nums);
System.out.println(str1);
}
else{//如果有奇数个汉字
String str1=new String(bytes,0,nums-1);
System.out.println(str1);
}
}
}我把题的意思理解错了,难怪那么难,我以为要用给定数字来把字符串分段,结果是截取前面半截,
一楼说的substring是什么意思啊?
unicode的英文前八位是0,这样来判断是否是汉字,
不过二楼的算法很好啊,直接看汉字数是否是奇数,这样简单多了,不过getbytes()默认的貌似不是unicode,搞不懂是啥子,总之英文还是一个字节,中文就是两个并且是负数
但是这些字符是极少极少被用到的,估计世界上也没多少人认识。非常不建议采用 getBytes() 的方法为进行判断,这种判断非常不好,很可能会造成半年汉字的存在,
再由于 getBytes() 是默认拆成字节数组的方式,是根据系统平台的字符集编码进行拆分的,在 Windows
下一般采用的是 GB18030 编码,而在 xNIX 系统中就不是使用这个编码了。
一: public class TestSplit { public static String split(String s,int n) { int d=n,i=0; while( i<s.length() && (d>1 || d==1 && s.charAt(i)<256) ) { if(s.charAt(i)<256) d--; else d-=2; i++; } return s.substring(0,i); } public static void main(String[] args) { System.out.println(split("我A汉BC字D",4)); System.out.println(split("我A汉BC字D",5)); System.out.println(split("我A汉BC字D",12)); }}
二: import java.util.ArrayList;
import java.util.Iterator;
public class Test{
int bytes;
ArrayList<String> list =new ArrayList<String>();
public Test(int bytes){
this.bytes=bytes;
} public void splitIt(String s){
if(s.getBytes().length<=bytes){ //判断字符串小于指定字节
list.add(s);
return ;
}
int temp=0;//字节标记
int i=0;//字符串标记 while(temp<bytes){//从字符串第一个字符开始统计,直到字节大于等于指定字节后跳出循环
temp+=(s.charAt(i++)+"").getBytes().length;
}
//System.out.println(temp);
if(temp==bytes){//如果temp刚好等于指定字节,就直接截取字符串
String s1 = s.substring(0,i);
list.add(s1);
splitIt(s.substring(i));//继续截取剩下的
}
else{
String s1 = s.substring(0,i-1);//如果temp大与指定字节,那就表示最后一个是汉字,就退一位截取字符串 list.add(s1);
splitIt(s.substring(i-1));//继续截取剩下的
}
}
public void print(){
System.out.println(list);
}
public static void main(String []args){
Test test1 = new Test(5);
test1.splitIt("dsad在现在是dsadas小");
test1.print();
}
}
等等
但是我怎么没有看懂啊,可以
给个注释吗?不好意思,对java的底层编码,也不是很清楚,还有什么unicode,gb...,iso8859-1等
public class Test1
{
public static void main(String args[])
{
String s="",s2="";
int num=0;
System.out.print("请输入您的字符串:");
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s=in.readLine();
}
catch(IOException e){}
System.out.print("请输入你要截取的字节数:");
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
s2=in.readLine();
}
catch(IOException e){}
num=Integer.parseInt(s2);
System.out.println("你的截取结果为:"+Separate(s,num));
}
public static String Separate(String s,int num)
{
String s2="";
for(int i=0;((i<num)&&(i<s.length()));i++)
{
if(s.charAt(i)>256) num--;
}
return s2=s.substring(0,num);
}
}
我试验了可以做 有错的地方希望大家指出。
public class Test {
private String t7(String str, int num) {//num表示一char进行截取的字符数
String reStr = str.substring(0,num);//substring函数也是以char进行字符的截取 不是以byte截取
if(str.length() == str.getBytes().length) {
//
}
else {
int len = str.getBytes().length;//获得字符串的字节
while (len > num){//字节数大于字符数 说明字符串中有汉字
reStr = reStr.substring(0,reStr.length()-1);
len = reStr.getBytes().length;
}
}
return reStr;
}
public static void main(String[]args) {
Test z = new Test();
String s = z.t7("我abc汉def",6);
System.out.println("result== "+s);
}
}
楼主可以看些我写的这个,不知道是否明白?
主要的思想是:如果截取的字符串中有汉字,则在字符创后面开始截取,(是以char截取而非byte截取)直到满足条件为止
对有中文的字符串getBytes()不带编码的做法很不专业啊。
有些编码如utf-8这么写代码就是错的。
public class CutString {
public String subString(String str, int num) throws Exception {
if (str != null && !"".equals(str)) {
char c;
for (int i = 0; i < num; i++) {
c = str.charAt(i);
if (isChinese(c)) {//是否是汉字
num--;
}
}
}
return str.substring(0, num);
} public boolean isChinese(char c) throws Exception {
return Character.toString(c).getBytes().length > 1;//汉字的unicode码为2
} public static void main(String[] args) throws Exception {
CutString cs = new CutString();
String s = cs.subString("我abc汉def", 6);
System.out.println(s);
}
}
* 编程:编写一个截取字符串的函数,输入为一个字符串和字节数
* 输出为按字节截取的字符串。
* 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”
* 输入“我ABC汉DEF”,应该输出为“我ABC”而不是“我ABC+汉的半个”
* */
public class TestSplit {
//十楼的方法
public static String split(String s, int n) {
int d = n, i = 0;
while (i < s.length() && (d > 1 || d == 1 && s.charAt(i) < 256)) { //这个逻辑判断台玄妙了
//这个应该就是判断是否为中文了,因为UINICODE规定,字母数组前8位为0,所以不可能大于256
if (s.charAt(i) < 256)
d--;
else
d -= 2;
i++;
}
return s.substring(0, i);
}
//我的方法
public static String myMethod(String s, int n) {
int count = 0;
for(int i = 0; i < s.length() && n>0; i++){ //遍历String
if(Character.getNumericValue(s.charAt(i))>0) //如果是中文,中文/英文标点,会返回-1
n--; //是英文,消去一个字节
else
n-=2; //是中文,消去二个字节
//每消去一次,代表要截取的char多了一个
//如果n<0也就是在最后只有一个字节可以消的时候,来了个中文:最后剩下1的时候又减去了2。如此就不要截取
if(n>=0)
count +=1;
}
return s.substring(0, count);
} public static void main(String[] args) {
System.out.println(split("我A汉BC字D", 1));
System.out.println(split("我A汉BC字D", 2));
System.out.println(split("我A汉BC字D", 3));
System.out.println(split("我A汉BC字D", 4));
System.out.println(split("我A汉BC字D", 5));
System.out.println(split("我A汉BC字D", 12));
System.out.println("---------------------------------");
System.out.println(myMethod("我A汉BC字D", 1));
System.out.println(myMethod("我A汉BC字D", 2));
System.out.println(myMethod("我A汉BC字D", 3));
System.out.println(myMethod("我A汉BC字D", 4));
System.out.println(myMethod("我A汉BC字D", 5));
System.out.println(myMethod("我A汉BC字D", 12));
//上述做法原理
//String转为byte[]后,按二进制位数来确定,8位为一个byte,而中文等一个字为16位
System.out.println("你好aa".getBytes().length); //6
//String的长度为字符数,而不论是8还是16位二进制
System.out.println("你好aa".length()); //4
//这个函数是按照String的长度来进行定位的
System.out.println("你好aa".charAt(0));
System.out.println("你好aa".charAt(1));
System.out.println("你好aa".charAt(2));
System.out.println("你好aa".charAt(3));
//中文字符转换为int值时,为-1,而标点不论中英文都为-1
System.out.println(Character.getNumericValue('a'));
System.out.println(Character.getNumericValue('1'));
System.out.println(Character.getNumericValue(','));
System.out.println(Character.getNumericValue('你'));
System.out.println(Character.getNumericValue('好'));
System.out.println(Character.getNumericValue(','));
//除去所有标点与数字,中文也是字母
System.out.println(Character.isLetter('你'));
System.out.println(Character.isLetter('1'));
System.out.println(Character.isLetter(','));
System.out.println(Character.isLetter('。'));
System.out.println(Character.isLetter('a')); }
}
System.out.println((int)'你');
System.out.println((int)'。');
System.out.println((int)'a');
System.out.println((int)',');
System.out.println((int)'6');20320
12290
97
44
54中文的字或标点都是很大的数字,而byte只有8位二进制而已,溢出了所以为-1