0

i want to replace same words with one of them

 "p1 p2 p2 p2 p2 p3 p3 p4 p5 p5 p5 p5 p5 p2 p2 p1 p1 p1"

to change this

 "p1 p2 p3 p4 p5 p2 p1"

is there any method in java to do this?

0

2 Answers 2

2

You can use regex.

String text = "p1 p2 p2 p2 p2 p3 p3 p4 p5 p5 p5 p5 p5 p2 p2 p1 p1 p1";
System.out.println(text.replaceAll("(\\w+)(\\s+\\1)+", "$1"));

output:

p1 p2 p3 p4 p5 p2 p1
  • (\\w+) will match single word and thanks to parenthesis it will be placed in group 1
  • in (\\s+\\1)+ \\s+ means one or more whitespace and \\1 requires same match as from group 1. Surrounding this with (...)+ requires this to exist one or more times
  • as replacement we used $1 which gets match stored in group 1 (so we are replacing many same words with first word).
Sign up to request clarification or add additional context in comments.

Comments

1

Here is one solution:

public static void main(String[] args)
{
    String s = "p1 p2 p2 p2 p2 p3 p3 p4 p5 p5 p5 p5 p5 p2 p2 p1 p1 p1";
    String[] parts = s.split(" ");
    ArrayList<String> arr = new ArrayList<String>();

    arr.add(parts[0]); // Add first item

    for (int i = 1; i < parts.length; i++) {
        if (!parts[i - 1].equals(parts[i])) { // Check if last item is different
            arr.add(parts[i]);
        }
    }

    StringBuilder sb = new StringBuilder();

    for (String str: arr) { // Creating the new String via StringBuilder
        sb.append(str);
        sb.append(" ");
    }

    System.out.println(sb.toString());
}

Output:

p1 p2 p3 p4 p5 p2 p1 

2 Comments

Small suggestion. Instead of appending str+" " use append(str).append(" "). This way you will not have to concatenate two Strings (and use another StringBuilder).
@Pshemo thanks for pointing it out. I don't know why I always overlook that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.