- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
A java string包含特殊字符(例如 ç
)的每个特殊字符占用两个字节的大小,但是 String length method或者使用从 getBytes method 返回的字节数组获取它的长度不返回计为两个字节的特殊字符。
如何正确计算字符串中的字节数?
示例:
单词 endereço
应该返回长度为 9 而不是 8。
最佳答案
The word endereço should return me length 9 instead of 8.
如果您希望长度为 8 个字符的 "endereço"
字符串的大小为 9 个字节:7 个 ASCII
字符和 1 个非 ASCII
字符,我想你想使用 UTF-8
字符集,它对 ASCII 表中包含的字符使用 1 个字节,对其他字符使用更多字节。
but String length method or getting the length of it with the byte array returned from getBytes method doesn't return special chars counted as two bytes.
String
length()
方法没有回答这个问题:使用了多少字节? 但是回答了:“有多少“UTF-16 代码单元”或更简单的 char
包含在其中?”
字符串
length()
Javadoc :
Returns the length of this string. The length is equal to the number of Unicode code units in the string.
不带参数的byte[]
getBytes()
方法将字符串编码为字节数组。您可以使用返回数组的 length
属性来了解编码字符串使用了多少字节,但结果将取决于编码期间使用的字符集。但是 byte[]
getBytes()
方法不允许指定字符集:它使用平台的默认字符集。
因此,如果底层操作系统默认使用的字符集不是您要用于以字节为单位对字符串进行编码的字符集,则使用它可能不会给出预期的结果。
此外,根据部署应用程序的平台,字符串以字节为单位的编码方式可能会发生变化。这可能是不受欢迎的。
最后,如果 String 不能在默认字符集中编码,则行为未指定。
因此,这种方法应该非常谨慎地使用或根本不使用。
byte[]
getBytes()
Javadoc :
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
The behavior of this method when this string cannot be encoded in the default charset is unspecified. The java.nio.charset.CharsetEncoder class should be used when more control over the encoding process is required.
在您的字符串示例 "endereço"
中,如果 getBytes()
返回一个大小为 8 而不是 9 的数组,这意味着您的操作系统不使用默认情况下 UTF-8
但字符集使用 1 字节固定宽度的字符,例如 ISO 8859-1
及其派生字符集,例如 windows-1252
基于 Windows 操作系统。
要了解应用程序运行的当前 Java 虚拟机的默认字符集,您可以使用此实用程序方法:Charset defaultCharset = Charset.defaultCharset()
。
解决方案
byte[]
getBytes()
方法带有另外两个非常有用的重载:
byte[] java.lang.String.getBytes(String charsetName) 抛出 UnsupportedEncodingException
byte[] java.lang.String.getBytes(Charset 字符集)
与不带参数的 getBytes()
方法相反,这些方法允许指定在字节编码期间使用的字符集。
byte[] java.lang.String.getBytes(String charsetName) 抛出 UnsupportedEncodingException
Javadoc :
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
The behavior of this method when this string cannot be encoded in the given charset is unspecified. The java.nio.charset.CharsetEncoder class should be used when more control over the encoding process is required.
byte[] java.lang.String.getBytes(Charset 字符集)
Javadoc :
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement byte array. The java.nio.charset.CharsetEncoder class should be used when more control over the encoding process is required.
您可以使用一个或另一个(虽然它们之间存在一些复杂性)将您的字符串编码为字节数组,使用 UTF-8 或任何其他字符集,并因此获得它的大小特定字符集。
例如,要使用 getBytes(String charsetName)
获取 UTF-8
编码字节数组,您可以这样做:
String yourString = "endereço";
byte[] bytes = yourString.getBytes("UTF-8");
int sizeInBytes = bytes.length;
你会得到你想要的9个字节的长度。
这是一个更全面的示例,显示了默认编码,默认字符集平台的字节编码,UTF-8
和 UTF-16
:
public static void main(String[] args) throws UnsupportedEncodingException {
// default charset
Charset defaultCharset = Charset.defaultCharset();
System.out.println("default charset = " + defaultCharset);
// String sample
String yourString = "endereço";
// getBytes() with default platform encoding
System.out.println("getBytes() with default charset, size = " + yourString.getBytes().length + System.lineSeparator());
// getBytes() with specific charset UTF-8
System.out.println("getBytes(\"UTF-8\"), size = " + yourString.getBytes("UTF-8").length);
System.out.println("getBytes(StandardCharsets.UTF_8), size = " + yourString.getBytes(StandardCharsets.UTF_8).length + System.lineSeparator());
// getBytes() with specific charset UTF-16
System.out.println("getBytes(\"UTF-16\"), size = " + yourString.getBytes("UTF-16").length);
System.out.println("getBytes(StandardCharsets.UTF_16), size = " + yourString.getBytes(StandardCharsets.UTF_16).length);
}
我基于 Windows 操作系统的机器上的输出:
default charset = windows-1252
getBytes() with default charset, size = 8
getBytes("UTF-8"), size = 9
getBytes(StandardCharsets.UTF_8), size = 9
getBytes("UTF-16"), size = 18
getBytes(StandardCharsets.UTF_16), size = 18
关于java - 如何正确计算字符串字节数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43195075/
如何使用 SPListCollection.Add(String, String, String, String, Int32, String, SPListTemplate.QuickLaunchO
我刚刚开始使用 C++ 并且对 C# 有一些经验,所以我有一些一般的编程经验。然而,似乎我马上就被击落了。我试过在谷歌上寻找,以免浪费任何人的时间,但没有结果。 int main(int argc,
这个问题已经有答案了: In Java 8 how do I transform a Map to another Map using a lambda? (8 个回答) Convert a Map>
我正在使用 node + typescript 和集成的 swagger 进行 API 调用。我 Swagger 提出以下要求 http://localhost:3033/employees/sear
我是 C++ 容器模板的新手。我收集了一些记录。每条记录都有一个唯一的名称,以及一个字段/值对列表。将按名称访问记录。字段/值对的顺序很重要。因此我设计如下: typedef string
我需要这两种方法,但j2me没有,我找到了一个replaceall();但这是 replaceall(string,string,string); 第二个方法是SringBuffer但在j2me中它没
If string is an alias of String in the .net framework为什么会发生这种情况,我应该如何解释它: type JustAString = string
我有两个列表(或字符串):一个大,另一个小。 我想检查较大的(A)是否包含小的(B)。 我的期望如下: 案例 1. B 是 A 的子集 A = [1,2,3] B = [1,2] contains(A
我有一个似乎无法解决的小问题。 这里...我有一个像这样创建的输入... var input = $(''); 如果我这样做......一切都很好 $(this).append(input); 如果我
我有以下代码片段 string[] lines = objects.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.No
这可能真的很简单,但我已经坚持了一段时间了。 我正在尝试输出一个字符串,然后输出一个带有两位小数的 double ,后跟另一个字符串,这是我的代码。 System.out.printf("成本:%.2
以下是 Cloud Firestore 列表查询中的示例之一 citiesRef.where("state", ">=", "CA").where("state", "= 字符串,我们在Stack O
我正在尝试检查一个字符串是否包含在另一个字符串中。后面的代码非常简单。我怎样才能在 jquery 中做到这一点? function deleteRow(locName, locID) { if
这个问题在这里已经有了答案: How to implement big int in C++ (14 个答案) 关闭 9 年前。 我有 2 个字符串,都只包含数字。这些数字大于 uint64_t 的
我有一个带有自定义转换器的 Dozer 映射: com.xyz.Customer com.xyz.CustomerDAO customerName
这个问题在这里已经有了答案: How do I compare strings in Java? (23 个回答) 关闭 6 年前。 我想了解字符串池的工作原理以及一个字符串等于另一个字符串的规则是
我已阅读 this问题和其他一些问题。但它们与我的问题有些无关 对于 UILabel 如果你不指定 ? 或 ! 你会得到这样的错误: @IBOutlet property has non-option
这两种方法中哪一种在理论上更快,为什么? (指向字符串的指针必须是常量。) destination[count] 和 *destination++ 之间的确切区别是什么? destination[co
This question already has answers here: Closed 11 years ago. Possible Duplicates: Is String.Format a
我有一个Stream一个文件的,现在我想将相同的单词组合成 Map这很重要,这个词在 Stream 中出现的频率. 我知道我必须使用 collect(Collectors.groupingBy(..)
我是一名优秀的程序员,十分优秀!