从Java中删除字符串中的空格

时间:2011-03-28 07:22:02

标签: java whitespace

我有一个这样的字符串:

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

我想删除字符串中的空格。我尝试了trim(),但这只删除了整个字符串之前和之后的空格。我也尝试了replaceAll("\\W", ""),但=也被删除了。

如何通过以下方式实现字符串:

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

36 个答案:

答案 0 :(得分:1222)

st.replaceAll("\\s+","")删除所有空格和不可见字符(例如,标签\n)。


st.replaceAll("\\s+","")st.replaceAll("\\s","")会产生相同的结果。

第二个正则表达式比第一个正则表达式快20%,但随着连续空格数量的增加,第一个正则表达式优于第二个正则表达式。


如果不直接使用,请将值分配给变量:

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

答案 1 :(得分:232)

replaceAll("\\s","")

\w =任何单词字符

\W =任何不是单词字符的内容(包括标点等)

\s =任何空格字符(包括空格,制表符等)

\S =任何不是空格字符的东西(包括字母和数字,以及标点符号等)

(编辑:正如所指出的,如果希望\s到达正则表达式引擎,则需要转义反斜杠,从而产生\\s。)

答案 2 :(得分:96)

问题的最正确答案是:

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

我刚从其他答案中修改了这段代码。我发布它是因为除了正是问题要求之外,它还表明结果作为新字符串返回,原始字符串未被修改,因为某些答案有点暗示。 / p>

(有经验的Java开发人员可能会说“当然,你实际上无法修改字符串”,但这个问题的目标受众可能不知道这一点。)

答案 3 :(得分:55)

replaceAll("\\s", "")怎么样?请参阅here

答案 4 :(得分:34)

处理字符串操作的一种方法是来自Apache commons的StringUtils。

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

你可以找到它here。 commons-lang包括更多,并得到很好的支持。

答案 5 :(得分:32)

如果您还需要删除不可破坏的空格,可以像这样升级代码:

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

答案 6 :(得分:28)

如果您更喜欢实用程序类到regex,那么Spring Framework中的StringUtils中有一个方法trimAllWhitespace(String)

答案 7 :(得分:25)

你已经从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]);
    }
  }
}
  

输出:
  name = john
  年龄= 13
  年= 2001年

答案 8 :(得分:20)

你应该使用

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

而不是:

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

这样,它将在每个字符串之间使用多个空格。 上述正则表达式中的+符号表示“一个或多个\ s”

答案 9 :(得分:7)

最简单的方法是使用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”。希望这会有所帮助。

答案 10 :(得分:7)

你可以通过

这么简单地完成
String newMysz = mysz.replace(" ","");

答案 11 :(得分:6)

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

答案 12 :(得分:4)

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

//它适用于任何空格 *不要忘记刺痛的空间

答案 13 :(得分:3)

使用模式和匹配它更具动态性。

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

答案 14 :(得分:3)

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

答案 15 :(得分:3)

在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 java.util.regex.Matcher;
import java.util.regex.Pattern;

我希望它会对你有所帮助。

答案 16 :(得分:3)

\W表示“非单词字符”。空白字符的模式为\s。这在Pattern javadoc中有详细记载。

答案 17 :(得分:2)

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

首先是空间,第二是没有空间。

然后就完成了。

答案 18 :(得分:2)

使用apache string util class最好避免NullPointerException

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

输出

abcdef

答案 19 :(得分:2)

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

答案 20 :(得分:1)

有很多方法可以解决这个问题。 你可以使用拆分功能或替换字符串的功能。

了解更多信息,请参阅smilliar问题http://techno-terminal.blogspot.in/2015/10/how-to-remove-spaces-from-given-string.html

答案 21 :(得分:1)

我正在尝试一个汇总答案,其中测试了删除字符串中所有空格的所有方法。 每种方法都运行一百万次,然后取平均值。注意:所有计算的总和将使用一些计算。


结果:

@jahir 's answer的第一名

  • 带短文本的StringUtils:1.21E-4毫秒(121.0毫秒)
  • 带有长文本的StringUtils:0.001648毫秒(1648.0毫秒)

第二名

  • 带有短文本的字符串生成器:2.48E-4毫秒(248.0毫秒)
  • 带有长文本的字符串生成器:0.00566 ms(5660.0 ms)

第三名

  • 带短文本的正则表达式:8.36E-4毫秒(836.0毫秒)
  • 带有长文本的正则表达式:0.008877毫秒(8877.0毫秒)

第四名

  • 短文本循环:0.001666 ms(1666.0 ms)
  • 对于长文本循环: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
                )
        );
    }
}

答案 22 :(得分:1)

要删除示例中的空格,这是另一种方法:

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

这样做是将它转换为一个数组,其中空格是分隔符,然后它将数组中的项组合在一起而没有空格。

它运作良好且易于理解。

答案 23 :(得分:1)

字符串中也存在其他空格。因此,我们可能需要从字符串中替换空格。

例如:无间断空间,3个电磁区域,标点空间

这是空格char http://jkorpela.fi/chars/spaces.html

的列表

所以我们需要修改

\ u2004我们获得三个PER-EM空间

s.replaceAll(“ [\ u0020 \ u2004]”,“”)

答案 24 :(得分:0)

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

这可能会有所帮助。

答案 25 :(得分:0)

如果要从字符串中删除所有空格:

public String removeSpace(String str) {
    String result = "";
    for (int i = 0; i < str.length(); i++){
        char c = str.charAt(i);        
        if(c!=' ') {
            result += c;
        }
    }
    return result;
}

答案 26 :(得分:0)

提供了很多答案。我想提供一个比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();

    }

}

答案 27 :(得分:0)

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


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

答案 28 :(得分:0)

您还可以查看下面的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

答案 29 :(得分:0)

科特林中使用st.replaceAll("\\s+","")时,请确保用{em> Regex 包裹"\\s+"

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

答案 30 :(得分:0)

可以使用Character类中的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);
}

答案 31 :(得分:0)

将每组文本分成自己的子字符串,然后连接这些子字符串:

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

答案 32 :(得分:-1)

您可以在不使用replaceAll()或Java中的任何预定义方法的情况下实现此目的。 这种方式是首选: -

public class RemoveSpacesFromString {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String newString;
        String str = "prashant is good" ;
        int i;
        char[] strArray = str.toCharArray();
        StringBuffer sb =  new StringBuffer();

        for(i = 0; i<strArray.length; i++)
        {
            if(strArray[i]!= ' ' && strArray[i]!= '\t')
            {
                sb.append(strArray[i]);
            }
        }
        System.out.println(sb);

        /*newString = str.replaceAll(" " , "");
        System.out.println(newString);*/
    }
}

答案 33 :(得分:-1)

package com.sanjayacchana.challangingprograms;

public class RemoveAllWhiteSpacesInString {

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

}

答案 34 :(得分:-2)

您想要的代码是

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

这将删除所有空格。

答案 35 :(得分:-5)

试试这个:

String str="name=john age=13 year=2001";
String s[]=str.split(" ");
StringBuilder v=new StringBuilder();
for (String string : s) {
    v.append(string);
}
str=v.toString();
相关问题