The function of trim(): removes the spaces at the beginning and end of the string.
public static void main(String arg[]){String a=" hello world ";String b="hello world";System.out.println(b.equals(a));a=a.trim();//Remove the spaces at the beginning and end of the string System.out.println(a.equals(b));} Execution results:
a: hello world ,false
a:hello world,true
Source code of trim():
public String trim() {
int arg0 = this.value.length;
//Get the length of this string
int arg1 = 0;
//Declare an int value and assign a value of 0
char[] arg2;
//Declare a char array
for (arg2 = this.value; arg1 < arg0 && arg2[arg1] <= 32; ++arg1) {
// Assign this character array to arg2 character array (the bottom layer of a java string is a character array, and this character array is the value attribute of the String class);
//Why is less than or equal to 32, please refer to the ASCII code table. ASCII table 32 represents a space, and there are tab tab characters below 32, /n newline characters, /r carriage return characters, /b backspace, etc.
//If a string is "123", then after the method is run, the value of arg1 will be assigned to 1.
;
}
while (arg1 < arg0 && arg2[arg0 - 1] <= 32) {
--arg0;
//If a string is "123", then after the method is run, arg0 will be assigned a value of 4
}
return arg1 <= 0 && arg0 >= this.value.length ? this : this.substring(arg1, arg0);
//arg1==1, so go back. this.substring(1,4)
//Including head but not tail, the result is "123"
}Summarize
The above is the entire content of this article about the function example and source code of the string.trim() function in java. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
" Java Source Code Analysis of HashMap Usage "
" Java Terminate Threading Instance and Stop() Method Source Code Reading "
" Analysis of ArrayList Source Code in Java Programming "
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!