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

时间:2022-12-07 22:28:24

I have a string like this:

我有这样一条线:

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

I want to remove the whitespaces in the string. I tried trim() but this removes only whitespaces before and after the whole string. I also tried replaceAll("\\W", "") but then the = also gets removed.

我想删除字符串中的空格。我尝试过trim(),但是这只删除了整条字符串前后的白字符。我还尝试了replaceAll(“\W”、“”),但是=也被删除。

How can I achieve a string with:

如何用:

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

27 个解决方案

#1


1126  

st.replaceAll("\\s+","") removes all whitespaces and non-visible characters (e.g., tab, \n).

删除所有的空白和不可见的字符(例如,tab, \n)。


st.replaceAll("\\s+","") and st.replaceAll("\\s","") produce the same result.

st.replaceAll(“\s+”)和st.replaceAll(“\s”)产生相同的结果。

The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one.

第二个regex比第一个快20%,但是随着连续空格的增加,第一个比第二个表现得更好。


Assign the value to a variable, if not used directly:

将值赋给变量,如果不直接使用:

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

#2


219  

replaceAll("\\s","")

\w = Anything that is a word character

任何单词字符

\W = Anything that isn't a word character (including punctuation etc)

任何非文字字符(包括标点等)

\s = Anything that is a space character (including space, tab characters etc)

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

\S = Anything that isn't a space character (including both letters and numbers, as well as punctuation etc)

\S =任何非空格字符(包括字母、数字、标点等)

(Edit: As pointed out, you need to escape the backslash if you want \s to reach the regex engine, resulting in \\s.)

(编辑:如前所述,如果您想让\s到达regex引擎,就需要转义反斜线,从而导致\s)。

#3


93  

The most correct answer to the question is:

这个问题最正确的答案是:

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

I just adapted this code from the other answers. I'm posting it because besides being exactly what the question requested, it also demonstrates that the result is returned as a new string, the original string is not modified as some of the answers sort of imply.

我只是把这段代码从其他答案中进行了修改。我之所以发布它,是因为它不仅是问题所要求的,它还演示了结果作为一个新的字符串返回,原始的字符串不像一些答案所暗示的那样被修改。

(Experienced Java developers might say "of course, you can't actually modify a String", but the target audience for this question may well not know this.)

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

#4


55  

How about replaceAll("\\s", ""). Refer here.

如何replaceAll(“\ \ "," ")。请参考这里。

#5


27  

If you prefer utility classes to regexes, there is a method trimAllWhitespace(String) in StringUtils in the Spring Framework.

如果您喜欢实用程序类而不喜欢regexes,那么在Spring框架的StringUtils中有一个方法trimAllWhitespace(String)。

#6


27  

If you need to remove unbreakable spaces too, you can upgrade your code like this :

如果您需要删除不可分割的空间,您可以像这样升级您的代码:

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

#7


25  

You've already got the correct answer from Gursel Koca but I believe that there's a good chance that this is not what you really want to do. How about parsing the key-values instead?

你已经得到了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]);
    }
  }
}

output:
name = john
age = 13
year = 2001

输出:name = john age = 13 year = 2001

#8


25  

One way to handle String manipulations is StringUtils from Apache commons.

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

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

You can find it here. commons-lang includes lots more and is well supported.

你可以在这里找到。common -lang包含更多内容,并且得到了很好的支持。

#9


17  

You should use

你应该使用

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

instead of:

而不是:

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

This way, it will work with more than one spaces between each string. The + sign in the above regex means "one or more \s"

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

#10


7  

You can do it so simply by

你这样做很简单

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


5  

The easiest way to do this is by using the org.apache.commons.lang3.StringUtils class of commons-lang3 library such as "commons-lang3-3.1.jar" for example.

最简单的方法是使用org.apache.common .lang3. stringutils类的commons-lang3库,如“commons-lang3-3.1”。jar”为例。

Use the static method "StringUtils.deleteWhitespace(String str)" on your input string & it will return you a string after removing all the white spaces from it. I tried your example string "name=john age=13 year=2001" & it returned me exactly the string that you wanted - "name=johnage=13year=2001". Hope this helps.

在输入字符串上使用静态方法“StringUtils.deleteWhitespace(String str)”,它会在删除所有空格后返回一个字符串。我尝试了您的示例字符串“name=johnage=13year=2001”,它返回给我您想要的字符串—“name=johnage=13year=2001”。希望这个有帮助。

#13


4  

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

//它适用于任何空间*别忘了在sting b中留出空间

#14


3  

\W means "non word character". The pattern for whitespace characters is \s. This is well documented in the Pattern javadoc.

\W的意思是“非文字字符”。空白字符的模式是\s。这在javadoc模式中得到了很好的说明。

#15


3  

In java we can do following operation:

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

for this you need to import following packages to your program:

为此,您需要导入以下软件包到您的程序:

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

i hope it will help you.

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

#16


2  

Using Pattern And Matcher it is more Dynamic.

使用模式和匹配器更动态。

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

#17


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

#18


2  

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

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

#19


1  

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

First with space, second without space.

先有空间,后无空间。

Then it is done.

然后就完成了。

#20


1  

there are many ways to solve this problem. you can use split function or replace function of Strings.

有许多方法可以解决这个问题。您可以使用拆分函数或替换字符串函数。

for more info refer smilliar problem http://techno-terminal.blogspot.in/2015/10/how-to-remove-spaces-from-given-string.html

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

#21


0  

To remove spaces in your example, this is another way to do it:

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

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

What this does is it converts it into an array with the spaces being the separators, and then it combines the items in the array together without the spaces.

它所做的是将它转换成一个数组,其中的空格作为分隔符,然后它将数组中的项目组合在一起,而不使用空格。

It works pretty well and is easy to understand.

它工作得很好,很容易理解。

#22


0  

Use apache string util class is better to avoid NullPointerException

使用apache string util类最好避免NullPointerException

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

Output

输出

abcdef

#23


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

This might help.

这可能会有所帮助。

#24


0  

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

将每组文本分离到它自己的子字符串中,然后将这些子字符串连接起来。前女友。

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

#25


-2  

You can achieve this without using replaceAll() or any Predefined Method in Java. this way is preferred:-

无需使用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);*/
    }
}

#26


-3  

The code you want is

您需要的代码是

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

This will remove all the white spaces.

这将删除所有空白。

#27


-4  

Try this

试试这个

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

#1


1126  

st.replaceAll("\\s+","") removes all whitespaces and non-visible characters (e.g., tab, \n).

删除所有的空白和不可见的字符(例如,tab, \n)。


st.replaceAll("\\s+","") and st.replaceAll("\\s","") produce the same result.

st.replaceAll(“\s+”)和st.replaceAll(“\s”)产生相同的结果。

The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one.

第二个regex比第一个快20%,但是随着连续空格的增加,第一个比第二个表现得更好。


Assign the value to a variable, if not used directly:

将值赋给变量,如果不直接使用:

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

#2


219  

replaceAll("\\s","")

\w = Anything that is a word character

任何单词字符

\W = Anything that isn't a word character (including punctuation etc)

任何非文字字符(包括标点等)

\s = Anything that is a space character (including space, tab characters etc)

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

\S = Anything that isn't a space character (including both letters and numbers, as well as punctuation etc)

\S =任何非空格字符(包括字母、数字、标点等)

(Edit: As pointed out, you need to escape the backslash if you want \s to reach the regex engine, resulting in \\s.)

(编辑:如前所述,如果您想让\s到达regex引擎,就需要转义反斜线,从而导致\s)。

#3


93  

The most correct answer to the question is:

这个问题最正确的答案是:

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

I just adapted this code from the other answers. I'm posting it because besides being exactly what the question requested, it also demonstrates that the result is returned as a new string, the original string is not modified as some of the answers sort of imply.

我只是把这段代码从其他答案中进行了修改。我之所以发布它,是因为它不仅是问题所要求的,它还演示了结果作为一个新的字符串返回,原始的字符串不像一些答案所暗示的那样被修改。

(Experienced Java developers might say "of course, you can't actually modify a String", but the target audience for this question may well not know this.)

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

#4


55  

How about replaceAll("\\s", ""). Refer here.

如何replaceAll(“\ \ "," ")。请参考这里。

#5


27  

If you prefer utility classes to regexes, there is a method trimAllWhitespace(String) in StringUtils in the Spring Framework.

如果您喜欢实用程序类而不喜欢regexes,那么在Spring框架的StringUtils中有一个方法trimAllWhitespace(String)。

#6


27  

If you need to remove unbreakable spaces too, you can upgrade your code like this :

如果您需要删除不可分割的空间,您可以像这样升级您的代码:

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

#7


25  

You've already got the correct answer from Gursel Koca but I believe that there's a good chance that this is not what you really want to do. How about parsing the key-values instead?

你已经得到了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]);
    }
  }
}

output:
name = john
age = 13
year = 2001

输出:name = john age = 13 year = 2001

#8


25  

One way to handle String manipulations is StringUtils from Apache commons.

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

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

You can find it here. commons-lang includes lots more and is well supported.

你可以在这里找到。common -lang包含更多内容,并且得到了很好的支持。

#9


17  

You should use

你应该使用

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

instead of:

而不是:

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

This way, it will work with more than one spaces between each string. The + sign in the above regex means "one or more \s"

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

#10


7  

You can do it so simply by

你这样做很简单

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


5  

The easiest way to do this is by using the org.apache.commons.lang3.StringUtils class of commons-lang3 library such as "commons-lang3-3.1.jar" for example.

最简单的方法是使用org.apache.common .lang3. stringutils类的commons-lang3库,如“commons-lang3-3.1”。jar”为例。

Use the static method "StringUtils.deleteWhitespace(String str)" on your input string & it will return you a string after removing all the white spaces from it. I tried your example string "name=john age=13 year=2001" & it returned me exactly the string that you wanted - "name=johnage=13year=2001". Hope this helps.

在输入字符串上使用静态方法“StringUtils.deleteWhitespace(String str)”,它会在删除所有空格后返回一个字符串。我尝试了您的示例字符串“name=johnage=13year=2001”,它返回给我您想要的字符串—“name=johnage=13year=2001”。希望这个有帮助。

#13


4  

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

//它适用于任何空间*别忘了在sting b中留出空间

#14


3  

\W means "non word character". The pattern for whitespace characters is \s. This is well documented in the Pattern javadoc.

\W的意思是“非文字字符”。空白字符的模式是\s。这在javadoc模式中得到了很好的说明。

#15


3  

In java we can do following operation:

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

for this you need to import following packages to your program:

为此,您需要导入以下软件包到您的程序:

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

i hope it will help you.

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

#16


2  

Using Pattern And Matcher it is more Dynamic.

使用模式和匹配器更动态。

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

#17


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

#18


2  

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

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

#19


1  

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

First with space, second without space.

先有空间,后无空间。

Then it is done.

然后就完成了。

#20


1  

there are many ways to solve this problem. you can use split function or replace function of Strings.

有许多方法可以解决这个问题。您可以使用拆分函数或替换字符串函数。

for more info refer smilliar problem http://techno-terminal.blogspot.in/2015/10/how-to-remove-spaces-from-given-string.html

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

#21


0  

To remove spaces in your example, this is another way to do it:

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

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

What this does is it converts it into an array with the spaces being the separators, and then it combines the items in the array together without the spaces.

它所做的是将它转换成一个数组,其中的空格作为分隔符,然后它将数组中的项目组合在一起,而不使用空格。

It works pretty well and is easy to understand.

它工作得很好,很容易理解。

#22


0  

Use apache string util class is better to avoid NullPointerException

使用apache string util类最好避免NullPointerException

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

Output

输出

abcdef

#23


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

This might help.

这可能会有所帮助。

#24


0  

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

将每组文本分离到它自己的子字符串中,然后将这些子字符串连接起来。前女友。

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

#25


-2  

You can achieve this without using replaceAll() or any Predefined Method in Java. this way is preferred:-

无需使用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);*/
    }
}

#26


-3  

The code you want is

您需要的代码是

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

This will remove all the white spaces.

这将删除所有空白。

#27


-4  

Try this

试试这个

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