【问题标题】:Java String ReplaceFirstJava 字符串替换优先
【发布时间】:2016-07-19 08:51:22
【问题描述】:

我正在阅读字符串

Is Mississippi a State where there are many systems.

我想用“t”或“T”替换每个单词中的第一个“s”或“S”(即保持相同的大小写)......这样输出是:

It Mitsissippi a Ttate where there are many tystems.

我试过了

s= s.replaceFirst("(?i)S", "t"); [which of course didn't work]

并尝试使用 string [] .split(Pattern.quote("\\s")) 然后试图弄清楚如何 replaceFirst() array 的每个元素,然后 return 将值返回到 string [但无法计算正确的做法]。

我认为\\G 可能有助于重新启动在下一个词,但没有得到任何地方。感谢您使用这 3 种方法的任何帮助。

【问题讨论】:

  • 如果只需要替换每部作品中的第一个's'或'S',为什么还要将'Is'替换为'It'?你能纠正一下布局并给出一个或多个清晰的例子吗?
  • 在每个 's' 或 'S' 的第一次出现时得到它
  • @Hedgebox 我希望你得到你的答案。但是提供了一种不同的方法来解决您的问题。看我的回答。
  • JavaScript 中的一行代码:.replace(/(\S*?)([sS])(\S*)/g, (_, $1, $2, $3) => $1 + ($2 == 's' ? 't' : 'T') + $3)

标签: java string replace split


【解决方案1】:

我创建了一个方法 -

  • 是通用的,
  • 不使用replacesplit,并且
  • 只使用一个循环。

以下是我的代码sn-p:

public static String replaceFirstOccurance(String sentence, char toChange, char changeWith) {
    StringBuilder temp = new StringBuilder();

    boolean changed = false;
    for (int i = 0; i < sentence.length(); i++) {
        if (!changed) {
            if (sentence.charAt(i) == toChange) {
                temp.append(changeWith);
                changed = true;
            } else if (sentence.charAt(i) == Character.toUpperCase(toChange)) {
                temp.append(Character.toUpperCase(changeWith));
                changed = true;
            } else {
                temp.append(sentence.charAt(i));
            }
        } else {
            if (sentence.charAt(i) == ' ') {
                changed = false;
            }
            temp.append(sentence.charAt(i));
        }
    }

    return temp.toString();
}

【讨论】:

    【解决方案2】:
    String ss = "Is Mississippi a State where there are many systems.";
    
    String out = "";//replaced string
    for (String s : ss.split(" ")) {
        int index = s.toUpperCase().indexOf('S');
        out += (s.replaceFirst("[s,S]", index!= -1 && s.charAt(index) == 'S' 
                   ? "T" : "t")) + " ";
    }
    
    System.out.println(out);
    

    【讨论】:

      【解决方案3】:

      使用以下对 Tim Biegeleisen 的答案的修正(在编辑他的帖子之前)

      String input = "Is Mississippi a State where there are many systems.";
      String[] parts = input.split(" ");
      StringBuilder sb = new StringBuilder("");
      
      for (String part : parts) {
          sb.append(part.replaceFirst("s", "t").replaceFirst("S", "T"));
          sb.append(" ");
      }
      
      System.out.println(sb.toString());
      

      编辑 - 您可以使用 concat()

      String input = "Is Mississippi a State where there are many systems.";
      String[] parts = input.split(" ");
      
      String output = "";
      
      for (String part : parts) {
          output = output.concat(part.replaceFirst("s", "t").replaceFirst("S", "T") + " ");
      }
      
          System.out.println(output);
      

      更新

          String input = "Is Mississippi a State where there are many Systems.";
          String[] parts = input.split(" ");
          //StringBuilder sb = new StringBuilder("");
      
          String output = "";
      
          for (String part : parts) {
              output = output.concat(part.replaceFirst("s", "t") + " ");
          }
      
          String[] parts2 = output.split(" ");
      
          output = "";
      
          for (String part : parts2) {
              output = output.concat(part.replaceFirst("S", "T") + " ");
          }
          System.out.println(output);
      

      【讨论】:

      • 我确实想使用 String 方法...有没有办法在不使用 StringBuilder 的情况下做到这一点?
      • @Hedgebox 仅供参考 StringBuilder 提供比+ 更好的性能
      • @Thush-Fdo: msandiford 在他下面的评论中......似乎是正确的......我刚刚尝试过......我希望“系统”成为“Tystems”......只有“S”或“s”第一次出现到“T”或“t”。当我将“系统”更改为“系统”时,代码会生成“Tyttems”而不是“Tystems”。
      • @Hedgebox :另一个解决方案是通过使用两个循环来解决这个问题,因为我已经更新了我的答案。但这会牺牲你的表现。随意使用任何建议。
      【解决方案4】:

      还有一个不错的、紧凑的、基于流的解决方案:

      String result = Stream.of(s.split(" "))
          .map(t -> t.replaceFirst("s", "t"))
          .map(t -> t.replaceFirst("S", "T"))
          .collect(Collectors.joining(" "));
      

      【讨论】:

        【解决方案5】:

        Approach-1:不使用replacesplit方法以获得更好的性能。

        String str = "Is Mississippi a State where there are many systems.";
        System.out.println(str);
        
        char[] cArray = str.toCharArray();
        boolean isFirstS = true;
        for (int i = 0; i < cArray.length; i++) {
            if ((cArray[i] == 's' || cArray[i] == 'S') && isFirstS) {
                cArray[i] = (cArray[i] == 's' ? 't' : 'T');
                isFirstS = false;
            } else if (Character.isWhitespace(cArray[i])) {
                isFirstS = true;
            }
        }
        str = new String(cArray);
        
        System.out.println(str);
        

        编辑:方法 2:因为您需要使用 replaceFirst 方法,而您不想使用 StringBuilder,这里有一个适合您的选项:

        String input = "Is Mississippi a State where there are many Systems.";
        String[] parts = input.split(" ");
        String output = "";
        
         for (int i = 0; i < parts.length; ++i) {
             int smallSIndx = parts[i].indexOf("s");
             int capSIndx = parts[i].indexOf("S");
        
             if (smallSIndx != -1 && (capSIndx == -1 || smallSIndx < capSIndx))
                 output += parts[i].replaceFirst("s", "t") + " ";
             else
                 output += parts[i].replaceFirst("S", "T") + " ";
         }
        
        System.out.println(output); //It Mitsissippi a Ttate where there are many Tystems. 
        

        注意:我更喜欢方法 1,因为它对于 replaceFisrt 和 @ 方法 没有开销 987654328@ , 字符串 appendconcat

        【讨论】:

        • @cricket_007 采用不同的方法编辑 :)
        • ASCII 移位...它会起作用,但它非常针对这一问题
        • @cricket_007 是的....但我希望这将提供比其他答案更快的解决方案。
        • @mmuzahid:感谢您的解决方案,但我正试图更好地了解 replaceFirst 的用途......此时不使用 StringBuilder。
        • @Hedgebox ,请参阅编辑部分,使用replaceFirst 可能有助于您的目的
        【解决方案6】:

        一种选择是将字符串拆分为单词,然后在每个单词上使用String.replaceFirst()s 的第一次出现替换为t(或您想要的任何其他字母):

        更新:

        我重构了我的解决方案以找到任何s(大写或小写)的第一次出现,并对其应用适当的转换。

        String input = "Is Mississippi a State where there are many systems.";
        String[] parts = input.split(" ");
        StringBuilder sb = new StringBuilder("");
        
        for (int i=0; i < parts.length; ++i) {
            if (i > 0) {
                sb.append(" ");
            }
            int index = parts[i].toLowerCase().indexOf('s');
            if (index >= 0 && parts[i].charAt(index) == 's') {
                sb.append(parts[i].replaceFirst("s", "t"));
            }
            else {
                sb.append(parts[i].replaceFirst("S", "T"));
            }
        }
        
        System.out.println(sb.toString());
        

        输出:

        It Mitsissippi a Ttate where there are many tystems.
        

        【讨论】:

        • @im-biegeleisen 您的解决方案经过一些调整非常完美。查看我的帖子
        • 对于像“Systems”这样带有大写“S”和小写“s”的单词,这会得到错误的结果(至少我理解这个问题)。
        • Systems -> Tyttems ...有什么问题?
        • @Tim Biegeleisen:msandiford 似乎是正确的......我刚刚尝试过......我希望“系统”成为“Tystems”......只有第一次出现“S”或“s”到“T”或“t”
        • @BDCoder 对不起,我有几个错别字。我已经修复了它们,并验证了实际输出是否符合预期。
        【解决方案7】:

        我的方法将较少依赖您提到的那些字符串方法。

        String phrase;
        String [] parts = phrase.split(" ");
        
        for (int i = 0; i < parts.length; i++ ) {
            for (int j = 0; j < parts[i].length(); j++) {
                if (parts[i].charAt(j) == 's') {
                    parts[i] = "t" + parts[i].substring(1);
                    break;
                } else if (parts[i].charAt(0) == 'S') {
                    parts[i] = "T" + parts[i].substring(1);
                    break;
                }
            }
        }
        
        String modifiedPhrase = "";
        
        for (int i = 0; i < parts.length; i++ ) {
            modifiedPhrase += parts[i] + " ";
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-27
          • 2015-05-02
          • 1970-01-01
          • 1970-01-01
          • 2022-11-21
          • 1970-01-01
          • 1970-01-01
          • 2015-12-23
          相关资源
          最近更新 更多