如何在数组中获得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];
}
但是在我运行之后,我所拥有的只是一个长长的随机字符串!
答案 0 :(得分: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];
}
答案 1 :(得分:1)
每次都要设置字符串数组,更改
stringsArray = [NSMutableArray arrayWithObject:randomString];
到
[stringsArray addObject:randomString];
你应该将randomString初始化移动到for循环中,否则你会将新的随机字符附加到同一个字符串