我想知道创建一个随机字符串的最好方法,但有一些简单的规则。
例如:(用户定义的长度,只能包含一个E,只能包含2-4个'S‘)
这将是Mac OSX应用程序的一部分,用户定义的项目将在UI中。用户设置参数并按下“生成”按钮。输出显示在NSTextField中。当然,我认为我可以处理UI部分,只有在有人想要包含示例代码的情况下才需要注意。谢谢。
发布于 2011-09-11 16:19:17
这是可行的,但请注意,理论上,它可能不会终止。您可能需要考虑将无关的Es和Ss替换为其他字母,以强制其终止。
如果用户输入的长度是2,它肯定会永远循环!
BOOL canQuit = NO;
while (!canQuit)
{
NSMutableString *output = [[[NSMutableString alloc] init] autorelease];
while ([output length] < userDefinedLength)
{
//Generates a random character between a and z;
char c = ((arc4random() % (122 - 96)) + 97);
[output appendFormat:@"%c", c];
}
NSLog(@"%@", output);
int numberOfE = [output replaceOccurrencesOfString:@"e" withString:@"e" options:NSCaseInsensitiveSearch range:NSMakeRange(0, output.length)];
int numberOfS = [output replaceOccurrencesOfString:@"s" withString:@"s" options:NSCaseInsensitiveSearch range:NSMakeRange(0, output.length)];
canQuit = (numberOfE <= 1 && numberOfS >= 2 && numberOfS <= 4);
}https://stackoverflow.com/questions/7376905
复制相似问题