如何不使用内置函数实现字符串length()?Java中如何无内置函数获字符串长度?
Hey there! Let's tackle these two string length problems one by one—they're great questions that dig into how strings work under the hood.
The core idea here is to iterate through the string, counting each character until we hit the end of the string. Since we can't use built-in length methods, we rely on detecting when we can no longer access a valid character.
Here's a platform-agnostic pseudocode implementation:
function customStringLength(str): count = 0 while True: try: // Attempt to access the character at position 'count' currentChar = str[count] count += 1 catch IndexOutOfBoundsException: // We've reached the end of the string—exit the loop break return count
How this works:
- We start with a counter set to 0.
- We keep trying to access the character at the current counter index. Each successful access means we have another character, so we increment the counter.
- When we try to access an index that doesn't exist, we catch the out-of-bounds exception and return the counter value—this is our string length.
In Java, the String class stores its content in an internal array (historically a char[], and in JDK 9+ a byte[] for compact strings). Since we can't use built-in methods like length() or charAt(), we can use reflection to directly access this internal array and get its length (note: array length is a field, not a method, so it doesn't count as a "built-in function" here).
Compatibility with most JDK versions (including JDK 9+):
import java.lang.reflect.Field; public class CustomStringLength { public static int getStringLength(String str) throws NoSuchFieldException, IllegalAccessException { // Get the internal "value" field that stores the string's content Field valueField = String.class.getDeclaredField("value"); valueField.setAccessible(true); Object contentArray = valueField.get(str); // Handle char[] (pre-JDK9) and byte[] (JDK9+ compact strings) if (contentArray instanceof char[]) { return ((char[]) contentArray).length; } else if (contentArray instanceof byte[]) { // For compact strings, check the coder to calculate length Field coderField = String.class.getDeclaredField("coder"); coderField.setAccessible(true); byte coder = coderField.getByte(str); // Coder 0 = Latin-1 (1 byte per char), coder 1 = UTF-16 (2 bytes per char) return coder == 0 ? ((byte[]) contentArray).length : ((byte[]) contentArray).length / 2; } return 0; } public static void main(String[] args) throws Exception { String testLatin = "Hello Stack Overflow!"; String testUtf16 = "你好,Java!"; System.out.println("Length of Latin string: " + getStringLength(testLatin)); System.out.println("Length of UTF-16 string: " + getStringLength(testUtf16)); } }
Notes:
- This approach relies on the internal implementation details of Java's
Stringclass. While this is consistent across most JDK distributions, it's possible (though unlikely) that future JDK versions might change these internal fields. - We use
setAccessible(true)to bypass the private access modifier on thevalueandcoderfields—this is standard for reflection-based access to internal class members.
内容的提问来源于stack exchange,提问作者menna abdallah

