program tip

자바에서 모든 공백을 제거하는 방법

radiobox 2020. 8. 14. 07:35
반응형

자바에서 모든 공백을 제거하는 방법


이 질문에 이미 답변이 있습니다.

프로그래밍 할당이 있고 그 중 일부는 사용자로부터 한 줄을 읽고 해당 줄 내의 모든 공백을 제거하는 코드를 만들어야합니다. 줄은 하나 이상의 단어로 구성 될 수 있습니다.

이 프로그램으로하려고했던 것은 공백을 찾을 때까지 각 문자를 분석 한 다음 해당 하위 문자열을 첫 번째 토큰으로 저장하는 것입니다. 그런 다음 더 이상 토큰이 없거나 줄 끝에 도달 할 때까지 다시 반복합니다.

나는 그것을 컴파일하려고 할 때 이것을 계속 얻습니다.

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)

다음은 코드입니다.

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

이 작업을 수행하는 더 쉬운 방법은 감사하지만이 프로그램이 작동하도록하고 싶습니다.

입력에 센티넬을 사용할 수 없습니다.


모든 도움에 감사드립니다.

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


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+","");

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.


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

yourString.replaceAll(" ","");

Replace all the spaces in the String with empty character.

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

Try:

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

s - indicates space character (tab characters etc)


Try this:

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

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.


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(" ", "");


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(" ", ""));

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.


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


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

String a="string with                multi spaces ";

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

//it work fine with any spaces

참고URL : https://stackoverflow.com/questions/15633228/how-to-remove-all-white-spaces-in-java

반응형