Rafi
Rafi

Reputation: 1922

iOS - Displaying Two Words At A Time From String Array

I'm doing an RSVP reading project app where it blinks words on the screen. You can set the word chunk size (how many words you want displayed at a time) to either 1, 2, or 3. I got it working for 1 word by having my paragraph in a string and doing:

[self.textInput componentsSeparatedByString:@" ";

This makes me an array of words that I can use to blink one word at a time. How would I be able to do this with displaying 2 words at a time? Is there a way I can use this function again to do it differently, or should I iterate over this word array and make a new one with 2 word strings?

Any help or advice would be greatly appreciated as to what the best practice would to get this done. Thanks.

Upvotes: 0

Views: 65

Answers (2)

Sam B
Sam B

Reputation: 27608

just like keith said create an array

NSArray *allwordsArray = [self.textInput componentsSeparatedByString:@" "];

Now you got all the info you need. Meaning you got the array with every word in it. Now its just a matter of putting it together. (I haven't tested this code)

    NSMutableArray *twoWordArray = [[NSMutableArray alloc] init];
    int counter=0;
    for (int i=0; i<[allwordsArray count]; i++)
    {
       if (counter >= [allwordsArray count]) break;
       NSString *str1 =  [NSString stringwithformat@"%@", [allwordsArray objectAtIndex:counter]];

       counter++;

         if (counter >= [allwordsArray count]) break;
         NSString *str2 =  [NSString stringwithformat@"%@", [allwordsArray objectAtIndex:counter]];
         NSString *combinedStr = [NSString stringwithformat@"%@ %@", str1,str2];
         [twoWordArray addObject: combinedStr];

         counter++;

    }

Upvotes: 1

keithbhunter
keithbhunter

Reputation: 12324

You have broken the string into components, which is on the right track. You could then make a smaller array that only includes components until you reach the chunk size. The final step would be to rejoin the string.

NSArray *components = [self.textInput componentsSeparatedByString:@" "];
NSRange chunkRange = NSMakeRange(0, chunkSize);
NSArray *lessComponents = [components subarrayWithRange:chunkRange];
NSString *newString = [lessComponents componentsJoinedByString:@" "];

Upvotes: 0

Related Questions