【问题标题】:How to remove single character in a string (java)?如何删除字符串中的单个字符(java)?
【发布时间】:2014-09-24 15:04:20
【问题描述】:

我有一个字符串类型的变量,我想从中删除所有单个字符。

示例:

String test = "p testing t testing";

我希望输出是这样的:

String test = "testing testing";

请帮帮我。谢谢。

【问题讨论】:

  • 用你想要的内容创建一个新的字符串。在构建新字符串之前,您可能希望使用 toCharArray 并单独处理字符。
  • 您不仅删除了单个字母,还删除了它们周围的(部分)空白。您是否只对长度大于 1 的单词感兴趣?您是否关心保留原始空白(多个空格、制表符等)?

标签: java string space


【解决方案1】:

您可能想要使用正则表达式并替换被空格包围的每个字符、输入的开头或结尾,并将其替换为单个空格,例如

String test = "p testing t testing".replaceAll("(^|\\s+)[a-zA-Z](\\s+|$)", " ");

这可能会在字符串的前面和结尾放置一个空格,因此您可能希望单独处理这些情况:

//first replace all characters surrounded by whitespace and the whitespace by a single space
String test = "p testing t testing".replaceAll("\\s+[a-zA-Z]\\s+", " ");

//replace any remaining single character with whitespace and either start or end of input next to it with nothing
test = test.replaceAll("(?>^[a-zA-Z]\\s+|\\s+[a-zA-Z]$)", "");

另一个提示:如果您想过滤 任何 类型的 字符(即 unicode 字符),您可能需要用 \p{L} 替换任何字母的 [a-zA-Z][\p{L}\p{N}] 表示任何字母或数字,\S 表示任何非空格。当然还有更多可能的字符类,所以请查看regular-expressions.info

最后说明:

虽然正则表达式是解决这个问题的一种“简单”且简洁的方法,但对于大型输入,它可能在很大程度上比拆分和重新连接要慢。您是否需要这种性能取决于您的需求和输入的大小。

【讨论】:

    【解决方案2】:

    使用正则表达式可以实现。

    试试这个替换衬里:

    String test = "p testing t testing z".replaceAll("\\b[a-z] \\b|\\b [a-z]\\b", "");

    【讨论】:

      【解决方案3】:
      String[] splitString = null;
      String test = "p testing t testing";
      splitString = test.split(" ");
      String newString = "";
      for(int i = 0; i < splitString.length; i++)
      {
         if(splitString[i].length() != 1)
         {
            newString += splitString[i] + " ";
         }
      }
      newString.trim();
      

      这将遍历拆分字符串并删除长度为 1 的字符串。

      【讨论】:

      • 在这里,拆分也是合理的,甚至可能比正则表达式更快(如果您需要那种速度),但我会让newString 成为StringBuilder
      • 是的,您可以改为使用 StringBuilder。
      【解决方案4】:
      String[] chunks = test.split("\\s+");
      
      String newtest = new String("");
      
      for ( String chunk : chunks)
      {
          if (chunk.length() > 1)
          {
              newtest+= chunk + " ";
          }
      }
      newtest = newtest.trim(); //to remove the last space
      

      【讨论】:

      • 我会为newtest 使用StringBuilder,否则你会得到大量用于大输入的中间字符串对象,这会损害内存和性能。
      • 你是对的,实际上你甚至可以重用测试字符串来避免分配更多的内存。
      • 好吧,重用测试字符串无济于事,因为对于每个newtest+= chunk + " ",您都会得到一个新的字符串对象 - 请记住,字符串是不可变的。
      【解决方案5】:

      1.按空格分割字符串。

      2.在字符串数组中检查每个字符串的长度并做出选择。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-17
        • 2013-02-01
        • 1970-01-01
        • 2011-05-29
        • 1970-01-01
        • 2013-08-20
        相关资源
        最近更新 更多