【问题标题】:How to replace substrings of string with different substrings in JAVA?如何在JAVA中用不同的子字符串替换字符串的子字符串?
【发布时间】:2022-01-22 13:28:42
【问题描述】:

我必须用不同的字符串替换单个字符串的不同子字符串。例如

 String str =" She was born on DATE at TIME on DAY";

我想用不同的字符串值替换字符串的 DATE、TIME 和 DAY 部分。使用replace(),我可以只替换字符串的一部分。但我正在寻找一种解决方案,一次用不同的字符串替换所有这些子字符串。

【问题讨论】:

  • 我认为这是不可能的。您应该显示您当前正在使用的代码。

标签: java string substring


【解决方案1】:

您可能做的最好的事情就是使用迭代正则表达式方法:

String str = "She was born on DATE at TIME on DAY";
Map<String, String> repl = new HashMap<>();
repl.put("DATE", "DATE_REPL");
repl.put("TIME", "TIME_REPL");
repl.put("DAY", "DAY_REPL");

Pattern pattern = Pattern.compile("\\b(DATE|TIME|DAY)\\b");
Matcher m = pattern.matcher(str);
StringBuffer buffer = new StringBuffer();
  
while(m.find()) {
    m.appendReplacement(buffer, repl.get(m.group(1)));
  }
m.appendTail(buffer);

System.out.println("input:  " + str);
System.out.println("output: " + buffer.toString());

打印出来:

input:  She was born on DATE at TIME on DAY
output: She was born on DATE_REPL at TIME_REPL on DAY_REPL

在这里,我们正在搜索正则表达式替换 \b(DATE|TIME|DAY)\b。每次在字符串中找到匹配项时,我们都会在 hashmap 中查找替换字符串。

【讨论】:

    【解决方案2】:

    这样做的最简单方法是将日期、时间和日期设为单独的变量,这样

    String str = "She was born on " + date + " at " + time + " on " + day;
    

    【讨论】:

      【解决方案3】:

      内置的字符串替换不支持替换多次出现。因此,您需要编写自己的方法来执行此操作。

      下面的代码假定oldstuff 包含唯一的字符串。如果它们不是唯一的,您将不得不编写不同的解决方案。

         public static void main(String[] args) {
              String original = " She was born on DATE at TIME on DAY";
              String[] oldstuff = {"DATE", "TIME", "DAY"};
              String[] newstuff = {"Feb 14, 2000", "midnight", "Tuesday"};
      
              System.out.println(original);
              String updated = replace(original, oldstuff, newstuff);
              System.out.println(updated);
      
          }
      
          static String replace(String str, String[] oldstuff, String[] newstuff) {
              for (int i = 0; i < oldstuff.length; i++) {
                  str = str.replace(oldstuff[i], newstuff[i]);
              }
              return str;
          }
      

      输出:

       She was born on DATE at TIME on DAY
       She was born on Feb 14, 2000 at midnight on Tuesday
      

      更好的解决方案是逐字扫描,只替换找到的匹配项。

          static String replace2(String str, String[] oldstuff, String[] newstuff){
              StringBuilder sb = new StringBuilder();
              java.util.Scanner s = new Scanner(str);
              int index = 0;
              while(s.hasNext()){
                  String word = s.next();
                  if (word.equals(oldstuff[index])){
                      sb.append(" ").append(newstuff[index]).append(" ");
                      index++;
                  } else {
                      sb.append(" ").append(word).append(" ");
                  }
              }
              
              return sb.toString();
          }
      
      

      【讨论】:

      • 请注意,这种方法的一个缺点是它需要单独调用 replace 来替换 each 关键字。
      • 是的,或者您可以逐个字符进行低级扫描以查找匹配项并使用 StringBuilder 构建新字符串。
      • 或使用扫描仪逐字扫描,将单词添加到字符串生成器。如果单词匹配,则添加替换而不是原始单词。
      【解决方案4】:

      一口气

      String str =" She was born on DATE at TIME on DAY";
      str = str.replaceAll("DATE", "2021-12-21").replaceAll("TIME", "11:20").replaceAll("DAY", "Tue");
      

      【讨论】:

        【解决方案5】:

        试试这个。

        public static void main(String[] args) {
            String str =" She was born on DATE at TIME on DAY";
        
            List<String> list = List.of("(date)", "(time)", "(day)");
            Iterator<String> iterator = list.iterator();
            String output = Pattern.compile("DATE|TIME|DAY").matcher(str)
                .replaceAll(m -> iterator.next());
        
            System.out.println(output);
        }
        

        输出:

         She was born on (date) at (time) on (day)
        

        或者

            Map<String, String> map = Map.of("DATE", "(date)", "TIME", "(time)", "DAY", "(day)");
            String output = Pattern.compile(String.join("|", map.keySet())).matcher(str)
                .replaceAll(m -> map.get(m.group()));
            System.out.println(output);
        

        【讨论】:

          【解决方案6】:

          您可以简单地使用 String.format("她于 %s 于 %s 出生于 %s",date ,time,day)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-11-09
            • 2023-03-25
            • 1970-01-01
            • 2012-04-03
            • 2013-07-23
            相关资源
            最近更新 更多