简体   繁体   English

根据字节长度修剪字符串

[英]Trim a string based on its byte length

I want to trim the string based on byte length (not character length), then how to achieve this? 我想根据字节长度(而不是字符长度)来修剪字符串,那么如何实现呢?

Example: String country = "日本日本日"; 例如: String country = "日本日本日";

One Japanese character will be 3 bytes. 一个日语字符将是3个字节。 Above string length is 5, byte length is 15. If I give 3, only 1st character should be printed. 上面的字符串长度为5,字节长度为15。如果输入3,则仅应打印第一个字符。 If I give 5, only 1st character should come, because 2 characters size is 6 bytes. 如果我给出5,则仅第一个字符应该出现,因为2个字符的大小为6个字节。 If I give 6, first 2 characters should be printed. 如果我给出6,则应该打印前2个字符。

Edit: Byte size varies depends on the String. 编辑:字节大小取决于字符串。 It may Japanese (or) Japanese with numerals (or) some other language. 它可以是日语(或日语)和数字(或其他语言)。

Divide your required byte with 3 and fetch those characters. 将所需的字节除以3,然后获取这些字符。 For ex. 对于前。

int requiredBytes = 5;
int requiredLength = 5 / 3;
System.out.println(country.subString(0,requiredLength));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM