Search code examples
javaalternating

String containing alternating words/numbers - printing words according to count


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.


Solution

  • Parse the number as an int, and then use this value to print the word as many times as you need:

    String[] array = {"7", "first", "3", "second", "2", "third", "4", "fourth", "2", "fifth"};
    for (int i=0; i < array.length; i+=2)
    {
       int count = Integer.parseInt(array[i]);
       for (int j=0; j < count; j++) {
           System.out.print(array[i+1]);
       }
       System.out.println();
    }
    

    count will get the values 7, 3, 2, etc.