[英]logic of java in-built method
誰能告訴我,在哪里可以找到java內置String方法的邏輯,例如length()
, tocharArray()
, charAt()
等...我曾嘗試對String.class
反編譯,但沒有發現它們的邏輯。 我想一個代碼來計算一個字符串的字符數,而無需使用任何內置的String類,但我無法破解如何突破成字符串的字符集,而無需使用字符串內置方法的想法..如String str = "hello";
如何將此字符串轉換為
'h' , 'e' , 'l' , 'l' , 'o'
這不是任何家庭作業...
請幫忙問候,希曼書
我一直使用http://grepcode.com 。 它通常具有我要查找的方法/對象的源代碼。 這是String類String.length()的 GC
編輯:至於第二個問題,如何計算字符串長度。 我會使用String.toCharArray()。 我希望您可以計算數組的長度。
整個字符串數據都保存在私有char array
字段中。
length()
只是:
public int length()
{
return this.value.length;
}
而且charAt(int)
並不復雜:
public char charAt(int paramInt)
{
if ((paramInt < 0) || (paramInt >= this.value.length)) {
throw new StringIndexOutOfBoundsException(paramInt);
}
return this.value[paramInt];
}
您正在尋找分離字符串字符的方法是toCharArray()
如果要反編譯.class
文件,請嘗試使用: http ://jd.benow.ca/它具有GUI應用程序和Eclipse IDE插件。
您可以在線查看OpenJDK源代碼。 確保您正在查看正確的代碼版本(庫版本和修訂版)。
例如,這是toCharArray()
的代碼:
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
這是charAt(int index)
:
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
您可以在這里找到String
類的源代碼。
如果不直接或間接使用String
無法使用它。 例如,您可以使用charAt(int index)
遍歷字符串字符,或創建一個StringBuilder(String s)
(內部調用String.length()
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.