-1

How can I use StringTokenizer to count how many times a number is present in a String if the numbers are separated with "_"? The String has to be entered through the command line.

For example if user enters:

1_3_34_12_1_2_34

the output will be

1_2, 3_1, 34_2, 2_1, 12_1
nkr
  • 3,026
  • 7
  • 31
  • 39
pidev
  • 131
  • 1
  • 1
  • 10

1 Answers1

0

Here is an example of what you can do

String input = "1_3_34_12_1_2_34";
String[] numbers = input.split("_");
Arrays.sort(numbers);
int count = -1;
String last = numbers[0];
for (String n : numbers) {
    count++;
    if (n.equals(last)) continue;
    System.out.print(last + '_' + count + ',');
    last = n;
    count = 0;
}
count++;
System.out.println(last + '_' + count);

prints

1_2,12_1,2_1,3_1,34_2

Hint: The order suggests you should use a LinkedHashMap<String, Integer>

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130