Java---練習(面接問題):文字列切り取り(1)
Javaでは、文字列「abcd」は文字列「abこんにちは」と同じ長さで4文字です.しかし、対応するバイト数は異なり、1つの漢字が2バイトを占めている.指定したバイト数でサブストリングを取得する方法を定義します.例えば、「abこんにちは」に対して、3バイト取ると、サブストリングはabと「あなた」の字の半分で、半分は捨てなければなりません.4バイトを取ると「abあなた」、5バイトを取るか「abあなた」を取るか.
上記はgbk符号化の下での切り取り文字列である.次はutf-8とgbk符号化で文字列を切り取るコードを書きます.
注意:utf-8のほとんどの漢字は3バイトであるため、簡略化のため、すべて3バイトとして扱われている.
GBKコードの次のテスト結果:
UTF-8の次のテスト結果:
今日はここまでです.
上記はgbk符号化の下での切り取り文字列である.次はutf-8とgbk符号化で文字列を切り取るコードを書きます.
注意:utf-8のほとんどの漢字は3バイトであるため、簡略化のため、すべて3バイトとして扱われている.
package io.string;
import java.io.IOException;
import java.util.Scanner;
public class StringCutOut {
static final String STR = " ";
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// GBK UTF-8
while (true) {
if (STR.getBytes().length % 2 == 0) {// GBK
System.out.println(" :( '#' )");
String str = sc.next();
if ("#".equals(str)) {
return;
}
System.out.println(" ( ):");
int n = sc.nextInt();
int len = 0;
int m = n;
while (len < str.length()) {
if (str.charAt(len) >= 0 && str.charAt(len) <= 128) {
n--;
System.out.print(str.charAt(len));
if (n <= 0) {
n = m;
System.out.println();
}
len++;
} else {
n -= 2;
System.out.print(str.charAt(len));
if (n <= 0) {
n = m;
System.out.println();
}
len++;
}
}
System.out.println();
} else if (STR.getBytes().length % 2 != 0) {// utf-8
System.out.println(" :( '#' )");
String str = sc.next();
if ("#".equals(str)) {
return;
}
str = new String(str.getBytes("gbk"), "UTF-8");
// gbk , 。 。。
// bug ----
// System.out.println(str);
// System.out.println(str.length());
System.out.println(" ( ):");
int n = sc.nextInt();
int len = 0;
int m = n;
while (len < str.length()) {
if (str.charAt(len) >= 0 && str.charAt(len) <= 128) {
n--;
System.out.print(str.charAt(len));
len++;
if (n <= 0) {
n = m;
System.out.println();
}
} else {
if(n-2<=0&&m>=3){
n=m;
System.out.println();
continue;
}
n -= 3;
System.out.print(str.charAt(len));
if(n<=0){
n=m;
System.out.println();
}
len++;
}
}
}
System.out.println();
}
}
}
GBKコードの次のテスト結果:
:( '#' )
ab
( ):
4
ab
UTF-8の次のテスト結果:
:( '#' )
ab
( ):
4
ab
今日はここまでです.