1

如何在数组中获取 5 个随机字符串?我试过这个:

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];
}

但是在我运行这个之后,我所拥有的只是一个长的随机字符串!

4

2 回答 2

1

你几乎拥有它。我认为这应该有效,但我还没有测试过。

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];
}
于 2013-11-07T16:45:29.747 回答
1

您每次都在设置字符串数组,请更改

stringsArray = [NSMutableArray arrayWithObject:randomString];

[stringsArray addObject:randomString];

并且您应该将 randomString 初始化移动到 for 循环中,否则您会将新的随机字符附加到同一字符串

于 2013-11-07T16:45:40.287 回答