java is a function that intercepts a string

  • 2020-06-12 09:03:31
  • OfStack

Write a function that intercepts a string with input of 1 string and number of bytes and output of string truncated by byte. But to ensure that the Chinese character is not truncated, such as "I ABC" 4, it should be truncated as "I AB", input "I ABC Han DEF", 6, output should be "I ABC" rather than "I ABC+ half of Han".

1. Need analysis

1, the input is a string and byte number, the output is a byte interception of the string -- according to the byte [byte] interception operation string, the first String into byte type
2, Chinese characters can not be cut half -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "Chinese characters cut half the corresponding bytes ASC code value is less than 0

2. Technical Difficulties

1. The ASC code corresponding to the half of a Chinese character is a value less than 0
2, string operation should be faced with a problem, whether the string is valid null, string length 0,1 this boundary processing

Code implementation:


package com.itheima;

/**
 * 10 ,   write 1 A function that intercepts a string, input is 1 The output is a byte truncated string. 
 *  But make sure the characters are not cut in half, such as "I" ABC " 4 "Should have been" I AB ", type "I ABC han DEF ", 6 "Should output as" I ABC "Instead of" I ABC+ Half of han ". 
 * 
 * @author 281167413@qq.com
 */

public class Test10 {

	public static void main(String[] args) {
		String srcStr1 = " I ABC";
		String srcStr2 = " I ABC han DEF";

		splitString(srcStr1, 4);
		splitString(srcStr2, 6);
	}

	public static void splitString(String src, int len) {
		int byteNum = 0;

		if (null == src) {
			System.out.println("The source String is null!");
			return;
		}

		byteNum = src.length();
		byte bt[] = src.getBytes(); //  will String Converted to byte An array of bytes 

		if (len > byteNum) {
			len = byteNum;
		}

		//  Determines whether or not a truncated, truncated word byte pairs ASC Code is less than 0 The value of the 
		if (bt[len] < 0) {
			String subStrx = new String(bt, 0, --len);
			System.out.println("subStrx==" + subStrx);
		} else {
			String subStrx = new String(bt, 0, len);
			System.out.println("subStrx==" + subStrx);
		}
	}

}

Results:


subStrx== I AB
subStrx== I ABC


Related articles: