I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:
String s = \"House, House
As mentioned by others use String::split(), followed by some map (hashmap or linkedhashmap) and then merge your result. For completeness sake putting the code.
import java.util.*;
public class Genric
{
public static void main(String[] args)
{
Map unique = new LinkedHashMap();
for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) {
if(unique.get(string) == null)
unique.put(string, 1);
else
unique.put(string, unique.get(string) + 1);
}
String uniqueString = join(unique.keySet(), ", ");
List value = new ArrayList(unique.values());
System.out.println("Output = " + uniqueString);
System.out.println("Values = " + value);
}
public static String join(Collection s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
}
New String is Output = House, Dog
Int array (or rather list) Values = [3, 4]
(you can use List::toArray) for getting an array.