Here is a Java program to remove all space characters from a string using replaceAll() method. In this java program, we have to delete all occurrences of space characters from a given string and then print it on screen.
For Example,Input String : Tech Crash Course
Output String : TechCrashCourse
Java program to remove all spaces from string using replaceAll method
In this java program, we will first take a string as input from user and store it in a String object "str". To delete all space characters from str, we will call replaceAll() method of String class. This method replaces any occurrence of space characters(including multiple adjacent space characters) with "". We are using "[ ]" regular expression, which matches with any space character.
package com.tcc.java.programs; import java.util.Scanner; public class DeleteSpaces { public static void main(String args[]) { String str, output; Scanner scanner = new Scanner(System.in); System.out.println("Enter a String"); str = scanner.nextLine(); output = str.replaceAll("[ ]", ""); System.out.println("Output String\n" + output); } }Output
Enter a String I love Java Programming Output String IloveJavaProgramming
Enter a String Java Programm to remove spaces Output String JavaProgrammtoremovespaces
Recommended Posts