133

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.

Community
  • 1
  • 1
Aiman Kh
  • 1,341
  • 2
  • 8
  • 4

14 Answers14

236

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+","");
kaysush
  • 4,797
  • 3
  • 27
  • 47
  • 3
    Is the `+` selector necessary in the regex when using replaceAll? – Kevin Bowersox Mar 26 '13 at 09:21
  • 6
    No its not necessary but if user enters more than one whitespace than this snippet will take care of such situations. – kaysush Mar 26 '13 at 09:23
  • 17
    Even without the `+` multiple spaces will get removed, since they will all match individually and be removed as one by one. – Lii Dec 21 '16 at 09:05
  • 1
    `replaceAll("\\p{Blank}","")` can also be used as it removes all the spaces and tabs from the String – CoderSam Aug 13 '19 at 07:20
76

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.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
66

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

yourString.replaceAll(" ","");
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • You're right. Makes sense. Why do you think "\\s" is more preferable? – moo cow Dec 28 '18 at 02:33
  • 1
    they are identical. `" "` is more intuitive, since novices can be not aware of literal `\s` – Rudziankoŭ Dec 28 '18 at 09:58
  • @Rudziankoŭ are they? Wouldn't `" "` match only space and not all whitespace? – Enerccio Feb 08 '20 at 10:23
  • @Enerccio, exactly! But `replaceAll` means it will apply to all characters in the sting. – Rudziankoŭ Feb 10 '20 at 08:39
  • @Rudziankoŭ but asker asked for whitespace, is `" "` is incorrect, it should be `\s` no? – Enerccio Feb 10 '20 at 14:03
  • Downvoted because this is answer is wrong; it shows how to remove a space but not all whitespaces. ISO/IEC/IEEE 24765:2010, term 3.3322 defines a whitespace as: "1. the nondisplaying formatting characters that are embedded within a block of free text. IEEE Std 1320.21998 (R2004) IEEE Standard for Conceptual Modeling Language Syntax and Semantics for IDEF1X97 (IDEFobject).3.1.210" – Pétur Ingi Egilsson Aug 08 '20 at 11:07
25

Replace all the spaces in the String with empty character.

String lineWithoutSpaces = line.replaceAll("\\s+","");
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
17

Try this:

String str = "Your string with     spaces";
str = str.replace(" " , "");
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
  • 2
    I guess this won't work with tabs. – Nitram76 Mar 26 '13 at 09:21
  • 1
    answer with tab is coverd here. http://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java – toidiu Feb 10 '15 at 04:50
  • Downvoted because this is answer is wrong; it shows how to remove a space but not all whitespaces. ISO/IEC/IEEE 24765:2010, term 3.3322 defines a whitespace as: "1. the nondisplaying formatting characters that are embedded within a block of free text. IEEE Std 1320.21998 (R2004) IEEE Standard for Conceptual Modeling Language Syntax and Semantics for IDEF1X97 (IDEFobject).3.1.210" – Pétur Ingi Egilsson Aug 08 '20 at 11:08
15

Try:

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

s - indicates space character (tab characters etc)

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
10
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.

7
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);


    }
}
Nick Freeman
  • 1,411
  • 1
  • 12
  • 25
4

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

Isaac
  • 56
  • 7
  • Exactly... isn't that the easiest way? – aashima Sep 21 '15 at 17:38
  • 1
    Downvoted because this is answer is wrong; it shows how to remove a space but not all whitespaces. ISO/IEC/IEEE 24765:2010, term 3.3322 defines a whitespace as: "1. the nondisplaying formatting characters that are embedded within a block of free text. IEEE Std 1320.21998 (R2004) IEEE Standard for Conceptual Modeling Language Syntax and Semantics for IDEF1X97 (IDEFobject).3.1.210" – Pétur Ingi Egilsson Aug 08 '20 at 11:09
3

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(" ", ""));
javadev
  • 1,639
  • 2
  • 17
  • 35
3
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

fatsoft
  • 81
  • 1
2
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.

AmitG
  • 10,365
  • 5
  • 31
  • 52
0
boolean flag = true;
while(flag) {
    s = s.replaceAll(" ", "");
    if (!s.contains(" "))
        flag = false;
}
return s;
Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
Lalit
  • 21
-10
String a="string with                multi spaces ";

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

//it work fine with any spaces

fatsoft
  • 81
  • 1
  • This does not remove all white space. It does not work on large strings of spaces. It does not take advantage of the built-in methods for handling spaces. Most of all, it does not solve the problem with the user's code. This is homework: removing the student's original solution does not serve the correct instructional purpose, unless that solution is fatally flawed. – Prune Feb 17 '16 at 00:04