The trim()
method of a String
class removes both leading and trailing white space from a string. In this example we use a regular expression to remove only the trailing white spaces from a string.
ppackage org.kodejava.example.lang;
public class TrailingSpace {
public static void main(String[] args) {
String text = " tattarrattat ";
System.out.println("Original = " + text);
System.out.println("text.length() = " + text.length());
// Using a regular expression to remove only the trailing white space in
// a string
text = text.replaceAll("\\s+$", "");
System.out.println("Result = " + text);
System.out.println("text.length() = " + text.length());
}
}
Original = tattarrattat
text.length() = 22
Result = tattarrattat
text.length() = 17
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020