java string. trim of function in the role of examples and source code

  • 2020-12-16 05:55:45
  • OfStack

trim() removes whitespace from the beginning and end of a 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 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

trim () source code:


public String trim() {
 int arg0 = this.value.length;
 // Gets the length of this string
 int arg1 = 0;
          // The statement 1 a int Value and assign a value of 0
 char[] arg2;
          // The statement 1 a char An array of
 for (arg2 = this.value; arg1 < arg0 && arg2[arg1] <= 32; ++arg1) {
     // Assigns this character array to arg2 Character array ( java The bottom of the string is an array of characters, and this array of characters is String Of the class value Attribute);
     // Why less than or equal to 32, Please see ASCII Clock, ASCII table 32 said 1 A space, 32 The following are tab Tabs, \n Line breaks, \r A carriage return, \b Backspace, etc.
     // if 1 The string is" 123 ", so this method is completed, arg1 Will be assigned a value of 1.
  ;
 }
 while (arg1 < arg0 && arg2[arg0 - 1] <= 32) {
  --arg0;
     // if 1 The string is" 123 ", so this method is completed, arg0 Will be assigned a value of 4
 }
 return arg1 <= 0 && arg0 >= this.value.length ? this : this.substring(arg1, arg0);
     //arg1==1, So walk behind. this.substring(1,4)
     // With head and without tail, the result is" 123 "
}

conclusion

Above is this article on java string. trim() function of the role of examples and source code all content, I hope to help you. Those who are interested can continue to see this site:

Java Source Code Analysis of HashMap Usage

Java Terminating Thread Instances and stop() Method Source Code Reading

ArrayList Source Code Analysis in Java Programming

If there is any deficiency, please let me know. Thank you for your support!


Related articles: