Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.
Java Program to Delete All Space Characters from a String
- 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 : BTechGeeks
Output String : BTechGeeks
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; /** * Java Program to remove all spaces from String */ 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(); // Deleting all space characters from given string // usnig replaceAll method 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