In this short article, we will write a Java program to remove or trim leading and trailing whitespace from the given String in Java.
Java Program to Remove Leading and Trailing White Space From a String
We are using built-in Character.isWhitespace() method to check if the first and last character is white space. Here is a complete Java program:
package com.javaguides.corejava.string;
/**
* @author Ramesh Fadatare
*
*/
public class StringTrimLeadingAndTrailingWhitespace {
public static void main(String[] args) {
String str = " Java Guides ";
String result = trimWhitespace(str);
System.out.println(result);
}
/**
* Trim leading and trailing whitespace from the given {@code String}.
* @param str the {@code String} to check
* @return the trimmed {@code String}
* @see java.lang.Character#isWhitespace
*/
public static String trimWhitespace(String str) {
if (!(str != null && !str.isEmpty())) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
sb.deleteCharAt(0);
}
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
Output:
Java Guides
Related String Programs
- Java program to Count Number of Duplicate Words in String
- Java Program to Count Number of Words in Given String
- Java Program to Count the Number of Occurrences of Substring in a String
- Java Program to Count the Occurrences of Each Character in String
- Java Program to Merge two String Arrays
- Java Program to Remove Duplicate Words from String
- Java Program to Reverse a String(5 ways)
- Java Program to Reverse Each Word of a String
- Java Program to Swap Two Strings
- How to Check if the String Contains only Digits
- How to Check if the String Contains only Letters
- How to Check If the String Contains Only Letters or Digits
- Java Program to Check if Input String is Palindrome
- Java Program to Find all Permutations of String
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course