gpt4 book ai didi

java - java 和 Scala 中非 Ascii 字符的子字符串

转载 作者:行者123 更新时间:2023-11-30 05:32:26 25 4
gpt4 key购买 nike

我无法在 java 或 scala 中找到使用 getBytes 中的绝对长度对非 ascii 字符执行子字符串的方法

 val string = "achâth33Franklin"

string.length
Int = 16

string.getBytes.length
Int = 17

string.substring(0,7)
String = achâth3

我需要一个产生 achâth 的方法,因为它具有长度为 2 的非 ascii 字符

 val test = "â"
test.getBytes.length
res26: Int = 2

提供更多看待问题的视角。

该字段的长度是常数,即7,它始终是ascii值。有时,它们会在字符串中发送非 ascii 值。结果子字符串(0,7),当它们非ascii值时将下一个字段值移动到当前值。

@VGR的解释

scala> val string = "achâth33Franklin"
string: String = achâth33Franklin

scala> new String(string.getBytes,0,7)
res30: String = achâth

scala> string.substring(0,7)
res31: String = achâth3

最佳答案

一种方法是将 getBytes() 结合起来方法 this constructor .

所以你的方法将如下所示:

String string = "achâth33Franklin";
string.substring(0,7); //achâth3
new String(string.getBytes(), 0, 7)); //achâth

该构造函数采用一个字节数组、数组中的偏移量以及要使用的字节数。所以 new String(string.getBytes(), a, b) 的工作逻辑与 string.substring(a, b) 相同,但是是按字节而不是按每个字节- 字符。

关于java - java 和 Scala 中非 Ascii 字符的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com