Java Online Compiler
Example: Remove Leading/Trailing Spaces using replaceAll() in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Remove Leading/Trailing Spaces using replaceAll() public class Main { public static void main(String[] args) { // Step 1: Define the input string with leading and trailing spaces String originalString = " Hello Java World "; System.out.println("Original String: '" + originalString + "'"); // Step 2: Use replaceAll() with a regular expression to target leading/trailing spaces // Regex explanation: // ^\\s+ : Matches one or more whitespace characters at the beginning of the string. // | : OR // \\s+$ : Matches one or more whitespace characters at the end of the string. String regex = "^\\s+|\\s+$"; String replacedString = originalString.replaceAll(regex, ""); // Step 3: Print the result System.out.println("Replaced String: '" + replacedString + "'"); } }
Output
Clear
ADVERTISEMENTS