【问题标题】:Removing whitespaces from string and removing them from char array [duplicate]从字符串中删除空格并将它们从字符数组中删除[重复]
【发布时间】:2017-05-06 15:13:40
【问题描述】:

我有一个在 java 中接收字符串的输入:

"a                                                a" 

(总共 50 个字符,2 个字母和 48 个空格)

当我尝试时

replace("\\s++","");

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

删除空格,但保留字符串(字符数组)与 '\u0000' 0 我如何删除它以使字符串仅包含 2 个字符?

【问题讨论】:

  • 你说的是哪个字符数组?完整的代码是什么?当您可以简单地使用 replace(" ", "") 时,为什么还要使用正则表达式?
  • 您是否期望 a only one space aa a 或究竟是什么?
  • 为什么要替换而不过滤字符?空格在哪里:开头,字符之间,结尾,...?
  • @rperes 解决方案有效。我很想改变我必须缩小的字符串,但感谢所有帮助和提示!

标签: java string replaceall


【解决方案1】:

首先,我要提醒您记住,函数replaceAll 返回一个新字符串并且不会更改原始字符串。 Java 中的字符串是immutable

然后要删除空格和'\u0000',只需这样做:

    String a = "a                                                a" ;
    a = a.replaceAll("[\\s\u0000]+","");   // set the result to a;
    System.out.println(a + " " + a.length());

输出:

aa 2

【讨论】:

    【解决方案2】:
       String str = "a                                                a" ;
    
       str = str.replaceAll(" ", "");
        System.out.println(str);
    

    【讨论】:

      猜你喜欢
      • 2016-06-04
      • 2019-05-21
      • 2011-09-21
      • 2023-03-29
      • 2017-11-20
      相关资源
      最近更新 更多