source

Java 문자열에서 공백 제거

goodcode 2022. 8. 28. 09:36
반응형

Java 문자열에서 공백 제거

나는 다음과 같은 끈이 있다.

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

끈의 여백을 제거하고 싶습니다.는 는 i i는노노 i i i i i.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 regex가 생성됩니다.\\s

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

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

다른 답변에서 이 코드를 수정한 것뿐입니다.이 글을 올리는 이유는 질문에서 요구한 것과 정확히 일치할 뿐만 아니라 결과가 새로운 문자열로 반환된다는 것을 보여주기 때문입니다.원래 문자열은 일부 답변이 암시하는 것처럼 수정되지 않았습니다.

(경험이 풍부한 Java 개발자는 "물론 스트링을 실제로 수정할 수는 없습니다"라고 말할 수 있지만, 이 질문의 대상 독자는 이 사실을 모를 수 있습니다.)

는 요?replaceAll("\\s", "")여기를 참조해 주세요.

문자열 조작을 처리하는 방법 중 하나는 Apache Commons의 String Utils입니다.

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

여기에서 찾을 수 있습니다. commons-lang은 훨씬 더 많이 포함되며 잘 지원됩니다.

분할할 수 없는 공간도 삭제할 필요가 있는 경우는, 다음과 같이 코드를 업그레이드할 수 있습니다.

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

를 사용해 주세요.

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

다음 대신:

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

이렇게 하면 각 문자열 사이에 공백이 여러 개 있을 때 작동합니다.위의 정규식에서 + 기호는 "1개 이상의 \s"를 의미합니다.

--\s = 공백 문자(스페이스, 탭 문자 등)의 임의의 문자.여기에 s+가 필요한 이유는 무엇입니까?

정규식보다 유틸리티 클래스를 원하는 경우 Spring Framework의 StringUtils에 trimAllWhitespace(String) 메서드가 있습니다.

당신은 이미 구르셀 코카로부터 정답을 맞췄지만, 나는 이것이 당신이 정말로 원하는 것이 아닐 가능성이 높다고 생각합니다.대신 key-values를 해석하는 것은 어떻습니까?

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

표시:
= = john
= = 13세
= 12월 21일 = 2001년

은 ""를 입니다.org.apache.commons.lang3.StringUtilscommons-lang3 등의 commons-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

문자열의 모든 공백을 제거하는 모든 방법을 테스트하는 집계 답변을 시도 중입니다.각 방법을 100만 번 실행한 후 평균을 구합니다.주의: 일부 계산은 모든 실행의 합계에 사용됩니다.


결과:

@jahir의 답변에서 1등

  • String Utils (짧은 텍스트 포함): 1.21E-4밀리초(121.0ms
  • 긴 텍스트의 String Utils: 0.001648 밀리초(1648.0 밀리초)

2위

  • 짧은 텍스트 문자열 빌더: 2.48E-4밀리초(248.0밀리초)
  • 긴 텍스트 문자열 빌더: 0.00566 ms (5660.0 ms)

3위

  • 짧은 텍스트 포함 정규식: 8.36E-4밀리초(836.0밀리초)
  • 긴 텍스트의 정규식: 0.008877 ms (8877.0 ms)

4위

  • 짧은 텍스트 루프: 0.001666ms(1666.0ms)
  • 긴 텍스트 루프일 경우: 0.086437밀리초(86437.0밀리초)

코드는 다음과 같습니다.

public class RemoveAllWhitespaces {
    public static String Regex(String text){
        return text.replaceAll("\\s+", "");
    }

    public static String ForLoop(String text) {
        for (int i = text.length() - 1; i >= 0; i--) {
            if(Character.isWhitespace(text.codePointAt(i))) {
                text = text.substring(0, i) + text.substring(i + 1);
            }
        }

        return text;
    }

    public static String StringBuilder(String text){
        StringBuilder builder = new StringBuilder(text);
        for (int i = text.length() - 1; i >= 0; i--) {
            if(Character.isWhitespace(text.codePointAt(i))) {
                builder.deleteCharAt(i);
            }
        }

        return builder.toString();
    }
}

테스트는 다음과 같습니다.

import org.junit.jupiter.api.Test;

import java.util.function.Function;
import java.util.stream.IntStream;

import static org.junit.jupiter.api.Assertions.*;

public class RemoveAllWhitespacesTest {
    private static final String longText = "123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222";
    private static final String expected = "1231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc222";

    private static final String shortText = "123 123 \t 1adc \n 222";
    private static final String expectedShortText = "1231231adc222";

    private static final int numberOfIterations = 1000000;

    @Test
    public void Regex_LongText(){
        RunTest("Regex_LongText", text -> RemoveAllWhitespaces.Regex(text), longText, expected);
    }

    @Test
    public void Regex_ShortText(){
        RunTest("Regex_LongText", text -> RemoveAllWhitespaces.Regex(text), shortText, expectedShortText);

    }

    @Test
    public void For_LongText(){
        RunTest("For_LongText", text -> RemoveAllWhitespaces.ForLoop(text), longText, expected);
    }

    @Test
    public void For_ShortText(){
        RunTest("For_LongText", text -> RemoveAllWhitespaces.ForLoop(text), shortText, expectedShortText);
    }

    @Test
    public void StringBuilder_LongText(){
        RunTest("StringBuilder_LongText", text -> RemoveAllWhitespaces.StringBuilder(text), longText, expected);
    }

    @Test
    public void StringBuilder_ShortText(){
        RunTest("StringBuilder_ShortText", text -> RemoveAllWhitespaces.StringBuilder(text), shortText, expectedShortText);
    }

    private void RunTest(String testName, Function<String,String> func, String input, String expected){
        long startTime = System.currentTimeMillis();
        IntStream.range(0, numberOfIterations)
                .forEach(x -> assertEquals(expected, func.apply(input)));
        double totalMilliseconds = (double)System.currentTimeMillis() - (double)startTime;
        System.out.println(
                String.format(
                        "%s: %s ms (%s ms)",
                        testName,
                        totalMilliseconds / (double)numberOfIterations,
                        totalMilliseconds
                )
        );
    }
}
mysz = mysz.replace(" ","");

첫째는 공간이 있고 둘째는 공간이 없습니다.

그러면 끝이다.

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

//어느 공간에서도 문제없이 작동 *스팅 b의 공간을 잊지 마십시오.

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

NullPointer를 피하려면 apache 문자열 util 클래스를 사용하는 것이 좋습니다.예외.

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

산출량

abcdef

\W는 "단어가 아닌 문자"를 의미합니다.은 「」입니다.\s이는 Pattern javadoc에 잘 설명되어 있습니다.

Java에서는 다음 작업을 수행할 수 있습니다.

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해야 합니다.

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

「」를 사용하고 st.replaceAll("\\s+","")코틀린에서 꼭 싸서"\\s+"Regex 사용 시:

"myString".replace(Regex("\\s+"), "")
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);
    }
}

예에서 공백을 제거하려면 다음 방법을 사용합니다.

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

이렇게 하면 공백이 구분 기호인 배열로 변환되고 공백 없이 배열 내의 항목을 결합합니다.

그것은 꽤 잘 작동하고 이해하기 쉽다.

이 문제를 해결할 수 있는 많은 방법이 있다.분할 함수를 사용하거나 Strings 함수를 대체할 수 있습니다.

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

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

예: 공백 없음, EM당 공간 3개, 구두점 공간

다음은 스페이스 문자 목록입니다.http://jkorpela.fi/chars/spaces.html

그래서 우리는 수정이 필요하다.

u2004년 3개의 EM당 공간 확보

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

공백은 문자 클래스에서 isWhitespace 함수를 사용하여 제거할 수 있습니다.

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

각 텍스트 그룹을 각각의 서브스트링으로 분리한 후 이들 서브스트링을 연결합니다.

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

이게 도움이 될 거야

아래의 Java 코드도 보실 수 있습니다.다음 코드에서는 "내장" 메서드를 사용하지 않습니다.

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

    }
}

입력:

String inp = "01239Debashish123Pattn456aik";

출력:

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

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

반응형

'source' 카테고리의 다른 글

앵커 태그가 있는 VueJ @click  (0) 2022.08.28
Java에서 long 초기화  (0) 2022.08.28
v-model 2 값은 어떻게 합니까?  (0) 2022.08.28
Vue Devtools가 로컬에서 작동하지 않음  (0) 2022.08.28
C 및 C++의 반환 보이드 유형  (0) 2022.08.28