【问题标题】:Java - Add numbers to matching wordsJava - 将数字添加到匹配的单词
【发布时间】:2015-03-25 19:35:48
【问题描述】:

我正在尝试为匹配的单词添加计数,如下所示:

匹配词:“文本”

输入:文本文本文本文本文本示例文本

输出:Text1 Text2 Text3 Text4Text5 ExampleText6

我试过这个:

String text = "Text Text Text TextText ExampleText";
String match = "Text";
int i = 0;
while(text.indexOf(match)!=-1) {
text = text.replaceFirst(match, match + i++);
}

不起作用,因为它会永远循环,匹配保留在字符串中并且 IndexOf 永远不会停止。

你会建议我做什么? 有更好的方法吗?

【问题讨论】:

  • 考虑使用两个字符串,一个用于原始数据,一个用于修改。可能的改进:使用 StringBuilder,使用正则表达式。
  • 创建第二个字符串,在其中写入已经“调整”的部分。然后,从原来的String中去掉,这样while indexof最终会返回-1

标签: java


【解决方案1】:

这里有一个StringBuilder,但不需要拆分:

public static String replaceWithNumbers( String text, String match ) {
    int matchLength = match.length();
    StringBuilder sb = new StringBuilder( text );

    int index = 0;
    int i = 1;
    while ( ( index = sb.indexOf( match, index )) != -1 ) {
        String iStr = String.valueOf(i++);
        sb.insert( index + matchLength, iStr );

        // Continue searching from the end of the inserted text
        index += matchLength + iStr.length();
    }

    return sb.toString();
}

【讨论】:

  • 酷。它看起来像我的解决方案。 ;-)
  • @SubOptimal 可能是。发之前我一直在测试,你可能之前发过。顺便说一句,当匹配的字符串是数字时,您是否测试过您的代码?
【解决方案2】:

首先取一个字符串缓冲区,即结果,然后用匹配(目标)溢出源。 它会产生一个空白数组和除“文本”之外的剩余单词。 然后检查 isempty 的条件并根据替换数组位置。

String text = "Text Text Text TextText ExampleText";
    String match = "Text";
    StringBuffer result = new StringBuffer();
    String[] split = text.split(match);
    for(int i=0;i<split.length;){
        if(split[i].isEmpty())
            result.append(match+ ++i);
        else
            result.append(split[i]+match+ ++i);
    }
    System.out.println("Result is =>"+result);

O/P 结果是 => Text1 Text2 Text3 Text4Text5 ExampleText6

【讨论】:

    【解决方案3】:

    试试这个解决方案测试过

        String text = "Text Text Text TextText Example";
        String match = "Text";
        String lastWord=text.substring(text.length() -match.length());
    
        boolean lastChar=(lastWord.equals(match));
    
        String[] splitter=text.split(match);
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<splitter.length;i++)
        {
    
           if(i!=splitter.length-1)
               splitter[i]=splitter[i]+match+Integer.toString(i);
           else
              splitter[i]=(lastChar)?splitter[i]+match+Integer.toString(i):splitter[i];
    
           sb.append(splitter[i]);
           if (i != splitter.length - 1) {
               sb.append("");
           }
        }
        String joined = sb.toString();
        System.out.print(joined+"\n");
    

    【讨论】:

    • 请给我你测试它的新文本。检查解决问题
    • @DeveloperH 使用例如text = "Text Text Text TextText ExampleTex"match = "Text" 结果是Text0 Text1 Text2 Text3Text4 ExampleTexText5。使用我的解决方案,它可以工作。 ;-)
    • 我刚刚完成了这个问题。
    【解决方案4】:

    一种可能的解决方案是

    String text = "Text Text Text TextText ExampleText";
    String match = "Text";
    StringBuilder sb = new StringBuilder(text);
    int occurence = 1;
    int offset = 0;
    while ((offset = sb.indexOf(match, offset)) != -1) {
        // fixed this after comment from @RealSkeptic
        String insertOccurence = Integer.toString(occurence);
        sb.insert(offset + match.length(), insertOccurence);
        offset += match.length() + insertOccurence.length();
        occurence++;
    }
    System.out.println("result: " + sb.toString());
    

    【讨论】:

      【解决方案5】:

      这对你有用:

      public static void main(String[] args) {
          String s = "Text Text Text TextText ExampleText";
          int count=0;
          while(s.contains("Text")){
              s=s.replaceFirst("Text", "*"+ ++count); // replace each occurrence of "Text" with some place holder which is not in your main String.
          }
          s=s.replace("*","Text");
          System.out.println(s);
      
      
      }
      

      O/P:

      Text1 Text2 Text3 Text4Text5 ExampleText6
      

      【讨论】:

      • 如果文本中有 * 怎么办?您应该使用其他符号,例如 Bell 字符或 smth。
      • @Milkmaid - 我正在编辑我的答案。你必须选择字符串中不存在的东西
      【解决方案6】:

      我将@DeveloperH 的代码重构为:

      public class Snippet {
      
          public static void main(String[] args) {
              String matchWord = "Text";
              String input = "Text Text Text TextText ExampleText";
              String output = addNumbersToMatchingWords(matchWord, input);
              System.out.print(output);
          }
      
          private static String addNumbersToMatchingWords(String matchWord, String input) {
              String[] inputsParts = input.split(matchWord);
      
              StringBuilder outputBuilder = new StringBuilder();
              int i = 0;
              for (String inputPart : inputsParts) {
                  outputBuilder.append(inputPart);
                  outputBuilder.append(matchWord);
                  outputBuilder.append(i);
                  if (i != inputsParts.length - 1)
                      outputBuilder.append(" ");
                  i++;
              }
              return outputBuilder.toString();
          }
      }
      

      【讨论】:

      • 干得好。我编辑我的答案。请检查我的答案,然后编辑你的
      【解决方案7】:

      我们可以通过使用 stringbuilder 来解决这个问题,它提供了最简单的构造来在字符串中插入字符。以下是代码

          String text = "Text Text Text TextText ExampleText";
          String match = "Text";
          StringBuilder sb = new StringBuilder(text);
          int beginIndex = 0, i =0;
          int matchLength = match.length();
          while((beginIndex = sb.indexOf(match, beginIndex))!=-1) {
               i++;
               sb.insert(beginIndex+matchLength, i);
               beginIndex++;
          }
          System.out.println(sb.toString());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-14
        • 1970-01-01
        相关资源
        最近更新 更多