1

How can I get 5 random strings in array? I tried this:

stringsArray = [[NSMutableArray alloc]init];
int string_lenght = 10;
NSString *symbols = @"ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuvwxyz";
NSMutableString *randomString = [NSMutableString stringWithCapacity:string_lenght];

for (int y = 0; y<5; y++) {
    for (int i = 0; i<string_lenght; i++) {
        [randomString appendFormat:@"%C", [symbols characterAtIndex:random()%[symbols length]]];
    }
    stringsArray = [NSMutableArray arrayWithObject:randomString];
}

But after I run this, all I have is one long random string!

2 Answers 2

1

you are setting the strings array each time, change

stringsArray = [NSMutableArray arrayWithObject:randomString];

to

[stringsArray addObject:randomString];

and you should move the randomString initialisation into the for loop, or you will be appending new random characters to the same string

Sign up to request clarification or add additional context in comments.

Comments

0

You almost had it. I think this should work, but I haven't tested it.

stringsArray = [[NSMutableArray alloc] init];
int string_length = 10;
NSString *symbols = @"ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuvwxyz";

for (int y = 0; y < 5; y++) 
{
    //Allocate a new "randomString" object each time, or you'll just add to the old one
    NSMutableString *randomString = [NSMutableString stringWithCapacity:string_length];
    for (int i = 0; i < string_length; i++) 
    { 
        char c = [symbols characterAtIndex:random() % [symbols length]];
        [randomString appendFormat:@"%c", c];
    }

    //Add the object to the array instead of replacing the entire array
    [stringsArray addObject:randomString];
}

1 Comment

You're welcome. =] Don't forget to mark an answer as correct when it helps you and optionally upvote it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.