Divided by the Java byte string

First, the subject description:

  A Java pen questions. The string according to the given number of bytes is divided, the divided output string. Characters can not be split requirements, such as "a Chinese" can not be split into "a + in half."

Second, the problem-solving ideas:

  String substring function firstly removed one by one like a character, the character may then be converted to an array of bytes, and determines the size of the accumulation to the counter, such as the condition and normalizing the output count condition is empty.

Third, the code:

public  class the Test {
     public  static  void main (String [] args) {
         / * ideas: the use of class String substring method one by one removed character string, it determines the number of bytes which will be converted to byte array and accumulated to the counter, when the counter output is greater than equal to k and resets the count condition * / 
        the Test T = new new the Test (); 
        t.subString ( "I love you China, I was born in China proud",. 3 ); 
    } 

    public  void subString (STR String, int K) { 
        String RES = "" ;
         int COUNT = 0 ;
         for ( int I = 0; I <str.length (); I ++ ) { 
            String tmpStr= str.substring(i,i+1);
            res += tmpStr;
            count += tmpStr.getBytes().length;
            if(count >= k){
                System.out.println(res);
                res = "";
                count = 0;
            }
            if(i == str.length()-1 && count < k){
                System.out.println(res);
            }
        }
    }
}

//输出

I love
you Zhong
States
I was
born in
China
and a sense of
the pride
proud

 

 

Guess you like

Origin www.cnblogs.com/chiweiming/p/11828965.html