How to Generate a random non-repeated(without repeating same alphabet) alphanumeric string from a given String in ios?
-
2stackoverflow.com/a/2633948/1186689– KDeogharkarOct 28, 2013 at 12:47
-
2possible duplicate of Generate a random alphanumeric string in cocoa– WainOct 28, 2013 at 12:53
-
how do you mean non-repeated? are you looking for unique string identifier in runtime?– holexOct 28, 2013 at 13:01
Add a comment
|
2 Answers
The following function will take a string and randomise it, usually each character from the input string only once:
- (NSString *)randomizeString:(NSString *)str
{
NSMutableString *input = [str mutableCopy];
NSMutableString *output = [NSMutableString string];
NSUInteger len = input.length;
for (NSUInteger i = 0; i < len; i++) {
NSInteger index = arc4random_uniform((unsigned int)input.length);
[output appendFormat:@"%C", [input characterAtIndex:index]];
[input replaceCharactersInRange:NSMakeRange(index, 1) withString:@""];
}
return output;
}
-(NSString *)randomStringWithLength: (int) len
{
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (int i=0; i<len; i++)
{
[randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}
return randomString;
}`