I have a Java string that contains numbers and words interchanged throughout as follows:
String str = "7 first 3 second 2 third 4 fourth 2 fifth"
I need to find a concise way (if possible) to print the words (first, second, third, fourth, fifth, etc.) the number of times shown.
The expected output is:
firstfirstfirstfirstfirstfirstfirst
secondsecondsecond
thirdthird
fourthfourthfourthfourth
fifthfifth
I tried to split the the string into an array and then use a for loop to iterate over every other number (in my outer loop) and every other word in my inner loop, but I was not successful.
Here is what I tried but I suspect this is not the correct approach or at the very least not the most concise one:
String[] array = {"7", "first", "3", "second", "2", "third", "4", "fourth", "2", "fifth"};
for (int i=0; i < array.length; i+=2)
{
// i contains the number of times (1st, 3rd, 5th, etc. element)
for (int j=1; j < array.length; j+=2)
// j contains the words (first, second, third, fourth, etc. element)
System.out.print(array[j]);
}
I'll be the first to admit I am very much a notice at Java, so if this approach is completely asinine please feel free to laugh, but thank you in advance for your assistance.