Java string truncation interview questions

Source: Internet
Author: User

Requirements:

Compile a function to intercept a string. The input is a string and number of characters, and the output is a string truncated by bytes. However, make sure that no half of Chinese characters are cut, for example, "my ABC" 4, it should be cut to "my AB", input "my ABC Han DEF", 6, the output should be "I abc" instead of "I ABC + Han ".

Basic knowledge:

First, let's take a look at the basic units:
1. bit is a binary bit. For example, 100011 is 6 bits.
2. bytes (byte), which is the most basic unit of data type in the computer. 8 bits constitute 1 byte.

Java needs to determine the size of the storage space occupied by each basic type. Their size does not change as the Random Device hardware architecture changes in most other languages. This immutability of the size of storage space is one of the reasons why java programs have the ability to shift values.

In java, the boolean length is 1 byte. In fact, it only takes 1 bit to work, and all others are 0.

The size of basic data in java is as follows:
Boolean 1-byte (in fact, 1bit is working)
Char 2-bytes
Byte 1-byte
Short 2-bytes
Int 4-bytes
Long 8-bytes
Float 4-bytes
Double 8-bytes
A letter or a Chinese character is a Unicode code unit, Unicode is currently widely used in UCS-2, it uses two bytes to encode a character, A character is a code unit in Unicode.

Code Public String splitString (String src, int size ){
String result = new String (src. getBytes (), 0, size );
If (! Src. startsWith (result )){
Result = new String (src. getBytes (), 0, size-1 );
}
Return result;
}

Note that if you use Eclipse to write a test program, set the text encoding to GBK. Otherwise, the results may be different.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.