Reputation: 25
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?
Upvotes: 0
Views: 80
Reputation: 34146
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
Upvotes: 1
Reputation: 124215
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(\\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$1
which gets match stored in group 1 (so we are replacing many same words with first word). Upvotes: 2