简体   繁体   中英

Java - Add numbers to matching words

I'm trying to add a count number for matching words, like this:

Match word: "Text"

Input: Text Text Text TextText ExampleText

Output: Text1 Text2 Text3 Text4Text5 ExampleText6

I have tried this:

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

Doesn't work because it would loop forever, the match stays in the string and IndexOf will never stop.

What would you suggest me to do? Is there a better way doing this?

Here is one with a StringBuilder but no need to split:

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();
}

first take one stringbuffer ie result,Then spilt the source with the match(destination). It results in an array of blanks and remaining words except "Text". then check condition for isempty and depending on that replace the array position.

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 Result is => Text1 Text2 Text3 Text4Text5 ExampleText6

Try this solution is tested

    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");

One possible solution could be

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());

This will work for you :

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

I refactored @DeveloperH 's code to this:

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();
    }
}

We can solve this by using stringbuilder, it provides simplest construct to insert character in a string. Following is the code

    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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM