共計 438 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
Java 中可以使用 getBytes() 方法將字符串轉(zhuǎn)換為字節(jié)數(shù)組,然后使用 Arrays.copyOfRange() 方法按指定的字節(jié)長度截取字節(jié)數(shù)組,最后再將截取的字節(jié)數(shù)組轉(zhuǎn)換為字符串。
下面是一個示例代碼:
public class ByteSubstring {public static void main(String[] args) {String str = "Hello, World!";
int length = 5; // 截取的字節(jié)長度
byte[] byteArray = str.getBytes(); // 將字符串轉(zhuǎn)換為字節(jié)數(shù)組
byte[] subArray = Arrays.copyOfRange(byteArray, 0, length); // 截取字節(jié)數(shù)組
String subStr = new String(subArray); // 將截取的字節(jié)數(shù)組轉(zhuǎn)換為字符串
System.out.println(subStr); // 輸出截取的字符串
}
}
運行上述代碼,輸出結(jié)果為:Hello
。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完