Java 从大字符串中一次读取一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9851359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:38:20  来源:igfitidea点击:

Reading one character at a time from a large string

javaarraysstring

提问by Ravi Joshi

I have a big string having at most 100000 character. Instead of using string.charAt[index]to read a character from the string, I converted that string into char array using string.toCharArray()method and now i am working with charArray[index]. which takes less time than string.charAt[index]method. However i want to know that, is there any other way which is faster than string.toCharArray();method?

我有一个最多包含 100000 个字符的大字符串。我没有使用string.charAt[index]从字符串中读取字符,而是使用string.toCharArray()方法将该字符串转换为 char 数组,现在我正在使用charArray[index]. 这比string.charAt[index]方法花费的时间少。但是我想知道,有没有比string.toCharArray();方法更快的其他方法?

采纳答案by nansen

I do not think there is a faster way. But please correct me!

我不认为有更快的方法。但请纠正我!

A String instance is backed by a char array. charAt() does some index checks which may be the cause for it being slower than working with the array returned by toCharArray(). toCharArray() simply does a System.arraycopy() of the backing array.

String 实例由 char 数组支持。charAt() 会做一些索引检查,这可能是它比使用 toCharArray() 返回的数组慢的原因。toCharArray() 只是对支持数组执行 System.arraycopy() 。