java怎样截取一定长度的字符串

Python018

java怎样截取一定长度的字符串,第1张

public static void main(String[] args) {

String ss="aaaaaaaaaaaaa"

int n=3

String s=null

int t=0

int a=ss.length()/n+1

for(int i=0i<ai++){

if(ss.length()>0){

t=ss.length()>n?n:ss.length()

s=ss.substring(0, t)

ss=ss.substring(t)

}

System.out.println(s)

}

}

java中截取未知长度字符串主要是使用String类,示例如下:

/**

 * @author cn

 * @param s 要截取的字符串

 * @param length 要截取字符串的长度->是字节一个汉字2个字节

 * return 返回length长度的字符串(含汉字)

*/

private static String getTitleToTen(String s, int length) throws Exception

    {

        byte[] bytes = s.getBytes("Unicode")

        int n = 0

        int i = 2

        for ( i < bytes.length && n < length i++){

         if (i % 2 == 0){

                n++

            }else{

                if (bytes[i] != 0){

                    n++

                }

            }

        }

        /*if (i % 2 == 1){

            if (bytes[i - 1] == 0)

                i = i - 1

            else

                i = i + 1

        }*/

        //将截一半的汉字要保留

        if (i % 2 == 1){

         i = i + 1

        }

        String eside = "................................................................."

        byte[] byteEside = eside.getBytes("Unicode")

        String title = ""

        if (bytes[i-1] == 0){

         title = new String(bytes, 0, i, "Unicode")+new String(byteEside,0,40,"Unicode")

        }else{

         title = new String(bytes, 0, i, "Unicode")+new String(byteEside,0,38,"Unicode")

        }

        return title

    }