第1期答案
上期问题:每日一问第1期 | 截取字符串
问题分析:
本题的思路是遍历字符串中的每个字符,然后判断字符串中的字符是英文还是中文,如果是英文就加1个字节,如果是中文就加2个字节,如果当前的字节数,小于等于传入的截取下标,就把这个字符加入到新的字符串中。Java在运行时采用utf16编码,中文字符占2个字节,所以编码大于256的字符就是中文。在Java中我们可以使用charAt()方法取出字符串中特定下标的字符。
代码:
package com.albertyy.AlbertYang;
/*
* 微信公众号:AlbertYang
*/
public class Day01 {
public static void main(String[] args) {
System.out.println(substitution("我ABC汉DEF",6));
}
/*
* 返回截取的字符串,要求字符串中的中文不能出现乱码:如(“我ABC”,4)应该截为“我AB”,
* 输入(“我ABC 汉DEF”,6)应该输出为“我ABC”而不是“我ABC+汉的半个”。
*/
private static String substitution(String str, int index) {
int count=0;
StringBuffer sb=new StringBuffer();
for (int i = 0; i < index; i++) {
char c=str.charAt(i);
if(c>256){
count+=2;
}else{
count+=1;
}
if(count<=index){
sb.append(c);
}
}
return sb.toString();
}
}
程序员小宋的答案:
public String subString(String str, int subBytes) {
int bytes = 0; // 用来存储字符串的总字节数
for (int i = 0; i < str.length(); i++) {
if (bytes == subBytes) {
return str.substring(0, i);
}
char c = str.charAt(i);
if (c < 256) {
bytes += 1; // 英文字符的字节数看作1
} else {
bytes += 2; // 中文字符的字节数看作2
if (bytes - subBytes == 1) {
return str.substring(0, i);
}
}
}
return str;
}
每日一问|今日问题
在Java中final, finally, finalize 的区别?