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

我有一个这样的字符串:

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

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

如何实现字符串:

mysz2 = "name=johnage=13year=2001"
1545058 次浏览

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


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

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


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

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

你已经从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=约翰
age=13
年=2001年

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

replaceAll("\\s","")

\w=任何是单词字符的东西

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

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

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

(编辑:如前所述,如果您希望\s到达regex引擎,则需要转义反斜杠,从而导致\\s

\W表示“非单词字符”。空格字符的模式是\s。这在模式javadoc中有很好的记录。

如果您更喜欢实用程序类而不是正则表达式,那么Spring Framework中的StringUtils中有一个方法修剪所有空白(字符串)

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

我希望它能帮助你。

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

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

我只是从其他答案中改编了这段代码。我发布它是因为除了正是问题所要求的,它还演示了结果作为新字符串返回,原始字符串不修改作为一些答案的暗示。

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

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

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

然后就完成了。

你想要的代码是

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

这将删除所有的空白。

你应该用

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

而不是:

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

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

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

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

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

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

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

如果你也需要删除不可破解的空格,你可以像这样升级你的代码:

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

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

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

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 newMysz = mysz.replace(" ","");
String a="string with                multi spaces ";//or thisString b= a.replaceAll("\\s+"," ");String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//它可以在任何空格下正常工作*不要忘记刺痛的空间b

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

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

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

试试这个:

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

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

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

public class RemoveSpacesFromString {
public static void main(String[] args) {// TODO Auto-generated method stubString 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);}}

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

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

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

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

使用apache字符串util类最好避免NullPointerException

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

产出

abcdef
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 Tabs += arr[i];}}return s;}

这可能会有帮助。

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

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

可以使用isWhitesspace函数从字符类中删除空白。

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

还有其他空间字符也存在于字符串中…所以我们可能需要从字符串中替换空间字符。

例如:无断裂空间、三电磁场空间、穿刺空间

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

所以我们需要修改

我们为每个EM三个空间

s.replaceAll("[]","")

静态编程语言中使用st.replaceAll("\\s+","")时,请确保将"\\s+"包装为Regex

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

提供了相当多的答案。我想给出一个可读性很强且比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();
}
}

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

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

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


结果:

第一名@jahir的回答

  • 带有短文本的StringUtils:1.21E-4 ms(121.0 ms)
  • 带有长文本的StringUtils: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)

第四名

  • 对于带有短文本的循环:0.001666 ms(1666.0 ms)
  • 对于长文本循环: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;
@Testpublic void Regex_LongText(){RunTest("Regex_LongText", text -> RemoveAllWhitespaces.Regex(text), longText, expected);}
@Testpublic void Regex_ShortText(){RunTest("Regex_LongText", text -> RemoveAllWhitespaces.Regex(text), shortText, expectedShortText);
}
@Testpublic void For_LongText(){RunTest("For_LongText", text -> RemoveAllWhitespaces.ForLoop(text), longText, expected);}
@Testpublic void For_ShortText(){RunTest("For_LongText", text -> RemoveAllWhitespaces.ForLoop(text), shortText, expectedShortText);}
@Testpublic void StringBuilder_LongText(){RunTest("StringBuilder_LongText", text -> RemoveAllWhitespaces.StringBuilder(text), longText, expected);}
@Testpublic 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));}}
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);        
        
}
}
public String removeSpaces(String word){StringBuffer buffer = new StringBuffer();if(word != null){char[] arr = word.toCharArray();for(int i=0; i < arr.length; i++){if(!Character.isSpaceChar(arr[i])) {buffer.append(arr[i]);}}}return buffer.toString();}