Java 中删除字符串中的空格

发布于 2024-10-26 21:01:29 字数 293 浏览 10 评论 0原文

我有一个这样的字符串:

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

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

我怎样才能获得一个字符串:

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

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.

How can I achieve a string with:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

岁月苍老的讽刺 2024-11-02 21:01:29

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


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

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


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

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

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


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

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.


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

st = st.replaceAll("\\s+","")
还给你自由 2024-11-02 21:01:29
replaceAll("\\s","")

\w = 任何单词字符

\W = 任何非单词字符(包括标点符号等)

\s = 任何单词这是一个空格字符(包括空格、制表符等)

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

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

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 = Anything that isn't a space character (including both letters and numbers, as well as punctuation etc)

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

橙幽之幻 2024-11-02 21:01:29

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

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

我刚刚从其他答案中改编了这段代码。我发布它是因为除了完全符合问题的要求之外,它还表明结果作为新字符串返回,原始字符串没有被修改,正如某些答案所暗示的那样。

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

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.)

快乐很简单 2024-11-02 21:01:29

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

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

您可以在此处找到它。
commons-lang 包含更多内容并且得到很好的支持。

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

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

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

爱你不解释 2024-11-02 21:01:29

replaceAll("\\s", "") 怎么样。请参阅此处

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

森林散布 2024-11-02 21:01:29

您应该使用

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

而不是:

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

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

--\s = 任何空格字符(包括空格、制表符等)。为什么这里需要 s+?

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"

--\s = Anything that is a space character (including space, tab characters etc). Why do we need s+ here?

只涨不跌 2024-11-02 21:01:29

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

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

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

st.replaceAll("[\\s|\\u00A0]+", "");
月寒剑心 2024-11-02 21:01:29

如果您更喜欢实用程序类而不是正则表达式,那么有一个方法 trimAllWhitespace(String)

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

听风吹 2024-11-02 21:01:29

您已经从 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

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?

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

廻憶裏菂餘溫 2024-11-02 21:01:29

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

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

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.

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.

三寸金莲 2024-11-02 21:01:29

你可以简单地做到这一点

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

You can do it so simply by

String newMysz = mysz.replace(" ","");
夜血缘 2024-11-02 21:01:29
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
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
如梦亦如幻 2024-11-02 21:01:29

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


结果:

@jahir 的回答

  • StringUtils 的短文本第一名:1.21E-4 ms (121.0 ms)
  • StringUtils with长文本:0.001648 ms (1648.0 ms)

第二名

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

第三名

  • 短文本正则表达式:8.36E-4 ms (836.0 ms)
  • 长文本正则表达式:0.008877 ms (8877.0 ms)

第四名

  • 短文本的 For 循环:0.001666 ms (1666.0 ms)
  • 长文本的 For 循环:0.086437 ms (86437.0 ms)

这是代码:

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

I am trying an aggregation answer where I test all ways of removing all whitespaces in a string.
Each method is ran 1 million times and then then the average is taken. Note: Some compute will be used on summing up all the runs.


Results:

1st place from @jahir 's answer

  • StringUtils with short text: 1.21E-4 ms (121.0 ms)
  • StringUtils with long text: 0.001648 ms (1648.0 ms)

2nd place

  • String builder with short text: 2.48E-4 ms (248.0 ms)
  • String builder with long text: 0.00566 ms (5660.0 ms)

3rd place

  • Regex with short text: 8.36E-4 ms (836.0 ms)
  • Regex with long text: 0.008877 ms (8877.0 ms)

4th place

  • For loop with short text: 0.001666 ms (1666.0 ms)
  • For loop with long text: 0.086437 ms (86437.0 ms)

Here is the code:

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

Here are the tests:

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
                )
        );
    }
}
诠释孤独 2024-11-02 21:01:29
mysz = mysz.replace(" ","");

第一个有空间,第二个没有空间。

然后就完成了。

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

First with space, second without space.

Then it is done.

梦太阳 2024-11-02 21:01:29
String a="string with                multi spaces ";
//or this 
String b= a.replaceAll("\\s+"," ");
String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//它适用于任何空格
*不要忘记b中的空格

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

晨与橙与城 2024-11-02 21:01:29

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

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

Kotlin 中使用 st.replaceAll("\\s+","") 时,请确保将 "\\s+" 用 < em>正则表达式:

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

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

"myString".replace(Regex("\\s+"), "")
宣告ˉ结束 2024-11-02 21:01:29

\W 表示“非单词字符”。空白字符的模式是 \s模式 javadoc

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

醉南桥 2024-11-02 21:01:29

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

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

In java we can do following operation:

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.

想挽留 2024-11-02 21:01:29

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

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

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);    
    }
}
情栀口红 2024-11-02 21:01:29

使用 apache string util 类最好避免 NullPointerException

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

Output

abcdef

Use apache string util class is better to avoid NullPointerException

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

Output

abcdef
讽刺将军 2024-11-02 21:01:29
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);
    }
}
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);
    }
}
时间海 2024-11-02 21:01:29

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

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

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

它工作得很好而且很容易理解。

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.

森林迷了鹿 2024-11-02 21:01:29
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);
        
        
    }

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

}
月寒剑心 2024-11-02 21:01:29

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

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

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

笛声青案梦长安 2024-11-02 21:01:29

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

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);
}
┾廆蒐ゝ 2024-11-02 21:01:29

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

例如:不间断空格、三个空格、标点符号空格

这是空格字符列表 http ://jkorpela.fi/chars/spaces.html

所以我们需要修改

\u2004 us 为三个空格

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

There are others space char too exists in strings.. So space char we may need to replace from strings.

Ex: NO-BREAK SPACE, THREE-PER-EM SPACE, PUNCTUATION SPACE

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

情域 2024-11-02 21:01:29

使用 hutool 的 StrUtil.cleanBlank(CharSequence str)

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.16</version>
</dependency>

use StrUtil.cleanBlank(CharSequence str) by hutool

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.16</version>
</dependency>

沫尐诺 2024-11-02 21:01:29

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

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

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);  
    }
}
死开点丶别碍眼 2024-11-02 21:01:29
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;
}

这可能会有所帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文