0

How to Generate a random non-repeated(without repeating same alphabet) alphanumeric string from a given String in ios?

Wain
  • 118,658
  • 15
  • 128
  • 151
ggg_1120
  • 398
  • 2
  • 19
  • 2
    http://stackoverflow.com/a/2633948/1186689 – KDeogharkar Oct 28 '13 at 12:47
  • 2
    possible duplicate of [Generate a random alphanumeric string in cocoa](http://stackoverflow.com/questions/2633801/generate-a-random-alphanumeric-string-in-cocoa) – Wain Oct 28 '13 at 12:53
  • how do you mean _non-repeated_? are you looking for unique string identifier in runtime? – holex Oct 28 '13 at 13:01

2 Answers2

4

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;
}
neilco
  • 7,964
  • 2
  • 36
  • 41
3
-(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;
}`
Jesse Onolemen
  • 1,277
  • 1
  • 15
  • 32
Nag Raj
  • 880
  • 1
  • 12
  • 18