I am having string array like this:
String[] str = new String[]{"foo","bar","foo","car"}
I need output like this:
bar1car1foo2
I tried like this:
String[] someArray = new String[] { "foo","bar","foo","car"};
for(int i=0;i<someArray.length;i++){
int count=0;
for(int j=0;j<someArray.length;j++){
if(someArray[i].equals(someArray[j])){
someArray[i] +=count;
}
}
System.out.println(someArray[i]);
}
and my output is:
foo0
bar0
foo0
car0
Python String count() Method The count() method returns the number of times a specified value appears in the string.
Python String has got an in-built function – string. count() method to count the occurrence of a character or a substring in the particular input string. The string. count() method accepts a character or a substring as an argument and returns the number of times the input substring happens to appear in the string.
One option is to use Map<String, Integer>
where the keys represent the individual strings, and the map value is the counter for each one.
So you can do something like:
Map<String, Integer> stringsWithCount = new TreeMap<>();
for (String item : str) {
if (stringsWithCount.contains(item)) {
stringsWithCount.put(item, stringsWithCount.get(item)+1));
} else {
stringsWithCount.put(item, 0);
}
}
And then you can iterate the map when done:
for (Entry<String, Integer> entry : stringsWithCount.entrySet()) {
and build your result string.
That was like the old-school implementation; if you want to be fancy and surprise your teachers, you can go for the Java8/lambda/stream solution:
Arrays.stream(str)
.collect(Collectors
.groupingBy(s -> s, TreeMap::new, Collectors.counting()))
.entrySet()
.stream()
.flatMap(e -> Stream.of(e.getKey(), String.valueOf(e.getValue())))
.collect(Collectors.joining())
But of course, you should be able to explain that piece of code.
public static void main(String args[]) {
String[] strArray = new String[] { "foo","bar","foo","car"};
countduplicate(strArray );
}
public static void countduplicate(String avalue[]) {
String str = "";
Set<String> set = new HashSet<String>();
for (int i = 0; i < avalue.length; i++) {
set.add(avalue[i]);
}
Iterator<String> iterator = set.iterator();
List<String> list = new ArrayList<String>();
while (iterator.hasNext()) {
int count=0;
str =iterator.next();
for (int i = 0; i < avalue.length; i++) {
if(str.equals(avalue[i])){
count++;
}
}
list.add(str+count);
}
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With