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 leading white spaces from a string.
package org.kodejava.lang;
public class LeadingSpace {
public static void main(String[] args) {
String text = " tattarrattat ";
System.out.println("Original = " + text);
System.out.println("text.length() = " + text.length());
// Using regular expression to remove only the leading white
// space in 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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024