[java] How to remove all white spaces in java

I have a programming assignment and part of it requires me to make code that reads a line from the user and removes all the white space within that line. the line can consist of one word or more.

What I was trying to do with this program is have it analyze each character until it finds a space and then save that substring as the first token. then loop again until it reaches no more tokens or the end of the line.

I keep on getting this when I try to compile it:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index   out of range: 1
    at java.lang.String.charAt(String.java:694)
    at trim.main(trim.java:23)

Here is the code

import java.util.Scanner ;
import java.lang.Character;
import java.lang.String ;
public class trim
{
        public static void main (String[]args)
        {

        String a  ;
        String b  ;
        String c ;
        char aChar ;
        int i = 0 ;

        Scanner scan = new Scanner(System.in);

        a = scan.nextLine();
        a =a.trim() ;


         for ( ; i >= 0 ; i++ )
         {
           aChar = a.charAt(i) ;
           if (aChar != 32)
           {
            a = a.substring(0,i+1);
           }
           else
           {
            b = a.substring(i,160) ;
            b= b.trim();
            c = c + a ;
            c = c.trim() ;
            a = b ;
            i = 0 ;
           }
           if (b.equals(null))
           {
            i = -1 ;
           }
         }
        }
}

easier ways to do this is appreciated, but I still want to get this program working.

and I can't use sentinels in the input.


Thanks everybody for all the help,

I will use the simpler method , and will read the javadoc.

This question is related to java string whitespace

The answer is


Why not use a regex for this?

a = a.replaceAll("\\s","");

In the context of a regex, \s will remove anything that is a space character (including space, tab characters etc). You need to escape the backslash in Java so the regex turns into \\s. Also, since Strings are immutable it is important that you assign the return value of the regex to a.


public static String removeSpace(String s) {
    String withoutspaces = "";
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) != ' ')
            withoutspaces += s.charAt(i);

    }
    return withoutspaces;

}

This is the easiest and most straight forward method to remove spaces from a String.


boolean flag = true;
while(flag) {
    s = s.replaceAll(" ", "");
    if (!s.contains(" "))
        flag = false;
}
return s;

Try this:

String str = "Your string with     spaces";
str = str.replace(" " , "");

The most intuitive way of doing this without using literals or regular expressions:

yourString.replaceAll(" ","");

String a="string with                multi spaces ";

String b= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//it work fine with any spaces


java.lang.String class has method substring not substr , thats the error in your program.

Moreover you can do this in one single line if you are ok in using regular expression.

a.replaceAll("\\s+","");

package com.infy.test;

import java.util.Scanner ;
import java.lang.String ;

public class Test1 {


    public static void main (String[]args)
    {

        String a  =null;


        Scanner scan = new Scanner(System.in);
        System.out.println("*********White Space Remover Program************\n");
        System.out.println("Enter your string\n");
    a = scan.nextLine();
        System.out.println("Input String is  :\n"+a);


        String b= a.replaceAll("\\s+","");

        System.out.println("\nOutput String is  :\n"+b);


    }
}

Cant you just use String.replace(" ", "");


Replace all the spaces in the String with empty character.

String lineWithoutSpaces = line.replaceAll("\\s+","");

You can use a regular expression to delete white spaces , try that snippet:

Scanner scan = new Scanner(System.in);
    System.out.println(scan.nextLine().replaceAll(" ", ""));

String a="string with                multi spaces ";
//or this 
String b= a.replaceAll("\\s+"," ");

String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//it work fine with any spaces

*don't forget space in sting b


Try:

  string output = YourString.replaceAll("\\s","")

s - indicates space character (tab characters etc)


trim.java:30: cannot find symbol
symbol  : method substr(int,int)
location: class java.lang.String
b = a.substr(i,160) ;

There is no method like substr in String class.

use String.substring() method.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to whitespace

How to create string with multiple spaces in JavaScript git: fatal: I don't handle protocol '??http' Show whitespace characters in Visual Studio Code What is the symbol for whitespace in C? How to print variables without spaces between values Trim whitespace from a String How do I escape spaces in path for scp copy in Linux? Avoid line break between html elements Remove "whitespace" between div element How to remove all white spaces in java