Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Java program to Remove spaces from a string

Remove spaces from String

For removing spaces from string , we’re going to code a java program in this article. Take string input from the user and store it in the variable called “s” in this case, After that convert that string to character array using toCharArray() method. Make a StringBuffer object and check each for each character array that element should not be blank there should not be any whitespaces if the condition is true append that element to StringBuffer object after that print StringBuffer object in which String doesn’t contain any blank spaces.

java program to remove spaces from string

Algorithm

  • Take string input from user and store it in the variable called “s”.
  • After that convert that string to char array using toCharArray() method.
  • Make a string buffer object and run the for loop start from i=0 to i<c.length.
  • check if( (c[i] != ‘ ‘) && (c[i]!= ‘\t’ )) append that character to string buffer and after that simply print string buffer.

Code in Java (Method-1 without using in-built method)

import java.util.Scanner;

public class RemoveAllWhiteSpacesFromAString {

	public static void main(String[] args) {
	  Scanner sc =new Scanner(System.in);
	  System.out.print("Enter a String :");
	  String s = sc.nextLine();
	  char[] c = s.toCharArray();
	  StringBuffer sb = new StringBuffer();
	  
	  
	  for (int i = 0; i < c.length; i++) {
	     if( (c[i] != ' ') && (c[i]!= '\t' )) {
	    	 sb.append(c[i]);
	     }    	
          }
	  System.out.println("String after removing spaces : "+sb);
    }
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Code in Java (Method-2 using in-built method)

import java.util.Scanner;

public class RemoveAllWhiteSpacesFromAString {
      public static void main(String[] args) {
      StringBuffer sb = new StringBuffer();
	String s = "www shubham nigam";
	String[] s1 = s.split("[\\s]");
	for (String string : s1) {
		sb.append(string);
	}
    System.out.println(sb);
   }
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Output

Enter a String : prep insta
String after removing spaces : prepinsta

2 comments on “Java program to Remove spaces from a string”


  • chetan

    String s1 = sc.nextLine();
    System.out.println(s1.replaceAll(“[ ]”,””));


  • Hrishi

    Easy Method:
    String s=”I love my India”;
    for (int i = 0; i < s.length(); i++) {

    if((s.charAt(i))!=' ') {
    System.out.print(s.charAt(i));