How to Trim Functions in Java
Using Java to trim a String is useful when you want to remove any leading and trailing white spaces from the String, such as when dealing with usernames and passwords. When displaying the first word of a String in a list, it may be preferable to display it like "first instead of as " first", with a leading white space. The Java String class has a built-in function for trimming off white spaces.
Instructions
-
-
1
Open your Java source file in an editor, such as Eclipse, JBuilder X or Netbeans.
-
2
Declare a Java String and assign it a value, by adding the code "String str = " text here ."
-
-
3
Call the "trim" method to remove any leading and trailing white spaces from the String, by adding the code "str.trim();." Using the previous example, " text here " becomes "text here."
-
4
Display the trimmed String with the "println" method by adding the code "System.out.println("trimmed String = " + str);."
-
5
Save the Java source file. Compile and run the program.
-
1