program tip

Java의 문자열에서 공백 제거

radiobox 2020. 10. 2. 21:58
반응형

Java의 문자열에서 공백 제거


다음과 같은 문자열이 있습니다.

mysz = "name=john age=13 year=2001";

문자열에서 공백을 제거하고 싶습니다. 시도 trim()했지만 이것은 전체 문자열 앞뒤의 공백 만 제거합니다. 나는 또한 시도 replaceAll("\\W", "")했지만 =또한 제거됩니다.

다음을 사용하여 문자열을 어떻게 얻을 수 있습니까?

mysz2 = "name=johnage=13year=2001"

st.replaceAll("\\s+","")모든 공백과 보이지 않는 문자 (예 : 탭, \n)를 제거합니다.


st.replaceAll("\\s+","")st.replaceAll("\\s","")동일한 결과를 생성한다.

두 번째 정규식은 첫 번째 정규식보다 20 % 빠르지 만 연속적인 공백 수가 증가하면 첫 번째 정규식이 두 번째 정규식보다 성능이 더 좋습니다.


직접 사용하지 않는 경우 값을 변수에 할당합니다.

st = st.replaceAll("\\s+","")

replaceAll("\\s","")

\w = 단어 문자 인 모든 것

\W = 단어 문자가 아닌 모든 것 (구두점 등 포함)

\s = 공백 문자 (공백, 탭 문자 등 포함) 인 모든 것

\S = 공백 문자가 아닌 모든 것 (문자와 숫자, 구두점 등 포함)

(편집 : 지적했듯이 \s정규식 엔진에 도달하려면 백 슬래시를 이스케이프해야 하므로 \\s.)


질문에 대한 가장 정답은 다음과 같습니다.

String mysz2 = mysz.replaceAll("\\s","");

나는 다른 답변 에서이 코드를 수정했습니다. 질문이 요청한 것과 정확히 일치하는 것 외에도 결과가 새 문자열로 반환 된다는 것을 보여주기 때문에 게시 하고 있습니다. 원래 문자열은 일부 답변이 암시하는 것처럼 수정되지 않습니다 .

(숙련 된 Java 개발자는 "물론 문자열을 실제로 수정할 수 없습니다"라고 말할 수 있지만이 질문의 대상 청중은 이것을 잘 모를 수 있습니다.)


방법에 대해 replaceAll("\\s", ""). 여기를 참조 하십시오 .


문자열 조작을 처리하는 한 가지 방법은 Apache commons의 StringUtils입니다.

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

여기에서 찾을 수 있습니다 . commons-lang은 더 많은 것을 포함하고 있으며 잘 지원됩니다.


깨지지 않는 공백도 제거해야하는 경우 다음과 같이 코드를 업그레이드 할 수 있습니다.

st.replaceAll("[\\s|\\u00A0]+", "");

regexes보다 유틸리티 클래스를 선호한다면 Spring Framework의 StringUtils에 trimAllWhitespace (String) 메서드가 있습니다.


당신은 이미 Gursel Koca로부터 정답을 얻었지만 이것이 당신이 정말로하고 싶은 것이 아닐 가능성이 높다고 믿습니다. 대신 키-값을 파싱하는 것은 어떻습니까?

import java.util.Enumeration;
import java.util.Hashtable;

class SplitIt {
  public static void main(String args[])  {

    String person = "name=john age=13 year=2001";

    for (String p : person.split("\\s")) {
      String[] keyValue = p.split("=");
      System.out.println(keyValue[0] + " = " + keyValue[1]);
    }
  }
}

출력 :
이름 = 존
나이 = 13
년 = 2001


당신은 사용해야합니다

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

대신에:

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

이 방법은 각 문자열 사이에 둘 이상의 공백으로 작동합니다. 위의 정규식에서 + 기호는 "하나 이상의 \ s"를 의미합니다.


이를 수행하는 가장 쉬운 방법 은 예를 들어 " " 와 같은 라이브러리 org.apache.commons.lang3.StringUtils클래스를 사용하는 것 입니다.commons-lang3commons-lang3-3.1.jar

StringUtils.deleteWhitespace(String str)입력 문자열에 정적 메서드 " "를 사용하면 모든 공백을 제거한 후 문자열을 반환합니다. 나는 당신의 예제 문자열 " name=john age=13 year=2001"을 시도했고 그것은 당신이 원하는 문자열 " "을 정확하게 반환했습니다 name=johnage=13year=2001. 도움이 되었기를 바랍니다.


간단하게 할 수 있습니다.

String newMysz = mysz.replace(" ","");

public static void main(String[] args) {        
    String s = "name=john age=13 year=2001";
    String t = s.replaceAll(" ", "");
    System.out.println("s: " + s + ", t: " + t);
}

Output:
s: name=john age=13 year=2001, t: name=johnage=13year=2001

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

// 어떤 공백에서도 잘 작동합니다. * sting b의 공백을 잊지 마세요.


\W"비 단어 문자"를 의미합니다. 공백 문자의 패턴은 \s입니다. 이것은 Pattern javadoc 에 잘 설명되어 있습니다.


자바에서는 다음과 같은 작업을 수행 할 수 있습니다.

String pattern="[\\s]";
String replace="";
part="name=john age=13 year=2001";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(part);
part=m.replaceAll(replace);
System.out.println(part);

이를 위해 다음 패키지를 프로그램으로 가져와야합니다.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

도움이 되길 바랍니다.


Pattern And Matcher를 사용하면 더 역동적입니다.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RemovingSpace {

    /**
     * @param args
     * Removing Space Using Matcher
     */
    public static void main(String[] args) {
        String str= "jld fdkjg jfdg ";
        String pattern="[\\s]";
        String replace="";

        Pattern p= Pattern.compile(pattern);
        Matcher m=p.matcher(str);

        str=m.replaceAll(replace);
        System.out.println(str);    
    }
}

사용하다 mysz.replaceAll("\\s+","");


mysz = mysz.replace(" ","");

첫 번째는 공백이고 두 번째는 공백입니다.

그런 다음 완료됩니다.


import java.util.*;
public class RemoveSpace {
    public static void main(String[] args) {
        String mysz = "name=john age=13 year=2001";
        Scanner scan = new Scanner(mysz);

        String result = "";
        while(scan.hasNext()) {
            result += scan.next();
        }
        System.out.println(result);
    }
}

아파치 문자열 util 클래스를 사용하면 NullPointerException을 피하는 것이 좋습니다.

org.apache.commons.lang3.StringUtils.replace("abc def ", " ", "")

산출

abcdef

이 문제를 해결하는 방법에는 여러 가지가 있습니다. 분할 기능을 사용하거나 문자열의 기능을 바꿀 수 있습니다.

자세한 내용은 smilliar 문제 http://techno-terminal.blogspot.in/2015/10/how-to-remove-spaces-from-given-string.html을 참조하십시오.


예제에서 공백을 제거하려면 다음과 같은 또 다른 방법이 있습니다.

String mysz = "name=john age=13 year=2001";
String[] test = mysz.split(" ");
mysz = String.join("", mysz);

이것이하는 일은 공백이 구분 기호 인 배열로 변환 한 다음 공백없이 배열의 항목을 함께 결합하는 것입니다.

꽤 잘 작동하고 이해하기 쉽습니다.


다른 공백 문자도 문자열에 존재합니다. 따라서 공백 문자를 문자열에서 대체해야 할 수도 있습니다.

예 : 중단없는 공간, EM 당 3 개의 공간, 구두점 공간

Here is the list of space char http://jkorpela.fi/chars/spaces.html

So we need to modify

\u2004 us for THREE-PER-EM SPACE

s.replaceAll("[\u0020\u2004]","")


When using st.replaceAll("\\s+","") in Kotlin, make sure you wrap "\\s+" with Regex:

"myString".replace(Regex("\\s+"), "")

White space can remove using isWhitespace function from Character Class.

public static void main(String[] args) {
    String withSpace = "Remove white space from line";
    StringBuilder removeSpace = new StringBuilder();

    for (int i = 0; i<withSpace.length();i++){
        if(!Character.isWhitespace(withSpace.charAt(i))){
            removeSpace=removeSpace.append(withSpace.charAt(i));
        }
    }
    System.out.println(removeSpace);
}

Separate each group of text into its own substring and then concatenate those substrings:

public Address(String street, String city, String state, String zip ) {
    this.street = street;
    this.city = city;
    // Now checking to make sure that state has no spaces...
    int position = state.indexOf(" ");
    if(position >=0) {
        //now putting state back together if it has spaces...
        state = state.substring(0, position) + state.substring(position + 1);  
    }
}

public static String removeWhiteSpaces(String str){
    String s = "";
    char[] arr = str.toCharArray();
    for (int i = 0; i < arr.length; i++) {
        int temp = arr[i];
        if(temp != 32 && temp != 9) { // 32 ASCII for space and 9 is for Tab
            s += arr[i];
        }
    }
    return s;
}

This might help.


You can also take a look at the below Java code. Following codes does not use any "built-in" methods.

/**
 * Remove all characters from an alphanumeric string.
 */
public class RemoveCharFromAlphanumerics {

    public static void main(String[] args) {

        String inp = "01239Debashish123Pattn456aik";

        char[] out = inp.toCharArray();

        int totint=0;

        for (int i = 0; i < out.length; i++) {
            System.out.println(out[i] + " : " + (int) out[i]);
            if ((int) out[i] >= 65 && (int) out[i] <= 122) {
                out[i] = ' ';
            }
            else {
                totint+=1;
            }

        }

        System.out.println(String.valueOf(out));
        System.out.println(String.valueOf("Length: "+ out.length));

        for (int c=0; c<out.length; c++){

            System.out.println(out[c] + " : " + (int) out[c]);

            if ( (int) out[c] == 32) {
                System.out.println("Its Blank");
                 out[c] = '\'';
            }

        }

        System.out.println(String.valueOf(out));

        System.out.println("**********");
        System.out.println("**********");
        char[] whitespace = new char[totint];
        int t=0;
        for (int d=0; d< out.length; d++) {

            int fst =32;



            if ((int) out[d] >= 48 && (int) out[d] <=57 ) {

                System.out.println(out[d]);
                whitespace[t]= out[d];
                t+=1;

            }

        }

        System.out.println("**********");
        System.out.println("**********");

        System.out.println("The String is: " + String.valueOf(whitespace));

    }
}

Input:

String inp = "01239Debashish123Pattn456aik";

Output:

The String is: 01239123456

private String generateAttachName(String fileName, String searchOn, String char1) {
    return fileName.replaceAll(searchOn, char1);
}


String fileName= generateAttachName("Hello My Mom","\\s","");

Quite a lot of answers are provided. I would like to give a solution which is quite readable and better than regex.

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

public class RemoveAllWhitespaceTest {

    public static void main(String[] args) throws IOException {

        String str1 = "\n\tThis is my string \n \r\n  !";

        System.out.println("[" + str1 + "]");

        System.out.println("Whitespace Removed:");

        System.out.println("[" + StringUtils.deleteWhitespace(str1) + "]");

        System.out.println();

    }

}

참고URL : https://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java

반응형