在Cocoa中生成一个随机的字母数字string

我想调用一个方法,传递它的长度,并生成一个随机的字母数字string。

有没有实用程序库,可能有一堆这些types的function?

这是一个快速和肮脏的实现。 还没有经过testing。

NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; -(NSString *) randomStringWithLength: (int) len { NSMutableString *randomString = [NSMutableString stringWithCapacity: len]; for (int i=0; i<len; i++) { [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length])]]; } return randomString; } 

不完全是你问的,但仍然有用:

 [[NSProcessInfo processInfo] globallyUniqueString] 

示例输出:

 450FEA63-2286-4B49-8ACC-9822C7D4356B-1376-00000239A4AC4FD5 
 NSString *alphabet = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789"; NSMutableString *s = [NSMutableString stringWithCapacity:20]; for (NSUInteger i = 0U; i < 20; i++) { u_int32_t r = arc4random() % [alphabet length]; unichar c = [alphabet characterAtIndex:r]; [s appendFormat:@"%C", c]; } 

当然你可以缩短这个时间:

 +(NSString*)generateRandomString:(int)num { NSMutableString* string = [NSMutableString stringWithCapacity:num]; for (int i = 0; i < num; i++) { [string appendFormat:@"%C", (unichar)('a' + arc4random_uniform(25))]; } return string; } 

杰夫B的答案的类别版本。

的NSString + Random.h

 #import <Foundation/Foundation.h> @interface NSString (Random) + (NSString *)randomAlphanumericStringWithLength:(NSInteger)length; @end 

的NSString + Random.m

 #import "NSString+Random.h" @implementation NSString (Random) + (NSString *)randomAlphanumericStringWithLength:(NSInteger)length { NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; NSMutableString *randomString = [NSMutableString stringWithCapacity:length]; for (int i = 0; i < length; i++) { [randomString appendFormat:@"%C", [letters characterAtIndex:arc4random() % [letters length]]]; } return randomString; } @end 

如果你只想限制自己到hex字符,那么最简单的select是生成一个UUID:

 NSString *uuid = [NSUUID UUID].UUIDString; 

输出示例: 16E3DF0B-87B3-4162-A1A1-E03DB2F59654

如果你想要一个较小的随机string,那么你可以抓住前8个字符。

这是一个版本4 UUID,这意味着第三和第四组中的第一个字符不是随机的(它们总是49AB )。

string中的其他每个字符都是完全随机的,您可以在数百年内每秒生成数以百万计的UUID,而不会产生两次相同UUID的风险。

你也可以生成一个UUID。 虽然不是真正的随机,但它们是复杂的和独特的,这使得它们在大多数用途中是随机的 生成一个string,然后取一个等于传递长度的字符范围。

这是解决这个问题的另一种方法。 您可以在整数和字符之间进行转换,而不是使用准备好的string,并生成要select的dynamic字符列表。 它非常精简,速度更快,但代码更多一些。

 int charNumStart = (int) '0'; int charNumEnd = (int) '9'; int charCapitalStart = (int) 'A'; int charCapitalEnd = (int) 'Z'; int charLowerStart = (int) 'a'; int charLowerEnd = (int) 'z'; int amountOfChars = (charNumEnd - charNumStart) + (charCapitalEnd - charCapitalStart) + (charLowerEnd - charLowerStart); // amount of the characters we want. int firstGap = charCapitalStart - charNumEnd; // there are gaps of random characters between numbers and uppercase letters, so this allows us to skip those. int secondGap = charLowerStart - charCapitalEnd; // similar to above, but between uppercase and lowercase letters. // START generates a log to show us which characters we are considering for our UID. NSMutableString *chars = [NSMutableString stringWithCapacity:amountOfChars]; for (int i = charNumStart; i <= charLowerEnd; i++) { if ((i >= charNumStart && i <= charNumEnd) || (i >= charCapitalStart && i <= charCapitalEnd) || (i >= charLowerStart && i <= charLowerEnd)) { [chars appendFormat:@"\n%c", (char) i]; } } NSLog(@"chars: %@", chars); // END log // Generate a uid of 20 characters that chooses from our desired range. int uidLength = 20; NSMutableString *uid = [NSMutableString stringWithCapacity:uidLength]; for (int i = 0; i < uidLength; i++) { // Generate a random number within our character range. int randomNum = arc4random() % amountOfChars; // Add the lowest value number to line this up with a desirable character. randomNum += charNumStart; // if the number is in the letter range, skip over the characters between the numbers and letters. if (randomNum > charNumEnd) { randomNum += firstGap; } // if the number is in the lowercase letter range, skip over the characters between the uppercase and lowercase letters. if (randomNum > charCapitalEnd) { randomNum += secondGap; } // append the chosen character. [uid appendFormat:@"%c", (char) randomNum]; } NSLog(@"uid: %@", uid); // Generate a UID that selects any kind of character, including a lot of punctuation. It's a bit easier to do it this way. int amountOfAnyCharacters = charLowerEnd - charNumStart; // A new range of characters. NSMutableString *multiCharUid = [NSMutableString stringWithCapacity:uidLength]; for (int i = 0; i < uidLength; i++) { // Generate a random number within our new character range. int randomNum = arc4random() % amountOfAnyCharacters; // Add the lowest value number to line this up with our range of characters. randomNum += charNumStart; // append the chosen character. [multiCharUid appendFormat:@"%c", (char) randomNum]; } NSLog(@"multiCharUid: %@", multiCharUid); 

当我正在做随机字符生成时,我更喜欢直接使用整数并将它们转换过来,而不是写出我想要绘制的字符列表。 在顶部声明variables使得它更独立于系统,但是这个代码假定数字的值比字母的值要小,而大写字母的值比小写字母的要小。

Swift中的替代解决scheme

 func generateString(len: Int) -> String { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let lettersLength = UInt32(countElements(letters)) let result = (0..<len).map { _ -> String in let idx = Int(arc4random_uniform(lettersLength)) return String(letters[advance(letters.startIndex, idx)]) } return "".join(result) } 

迅速

 func randomStringWithLength(length: Int) -> String { let alphabet = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" let upperBound = UInt32(count(alphabet)) return String((0..<length).map { _ -> Character in return alphabet[advance(alphabet.startIndex, Int(arc4random_uniform(upperBound)))] }) } 

Melvin给出了一个很好的答案,下面是一个函数( 在SWIFT中 )获得一个随机string:

 func randomStringOfLength(length:Int)->String{ var wantedCharacters:NSString="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789" var s=NSMutableString(capacity: length) for (var i:Int = 0; i < length; i++) { let r:UInt32 = arc4random() % UInt32( wantedCharacters.length) let c:UniChar = wantedCharacters.characterAtIndex( Int(r) ) s.appendFormat("%C", c) } return s } 

这是从randomStringOfLength(10)调用的一个testing结果: uXa0igA8wm

生成给定长度的小写字母数字随机string:

 -(NSString*)randomStringWithLength:(NSUInteger)length { NSMutableString* random = [NSMutableString stringWithCapacity:length]; for (NSUInteger i=0; i<length; i++) { char c = '0' + (unichar)arc4random()%36; if(c > '9') c += ('a'-'9'-1); [random appendFormat:@"%c", c]; } return random; } 

如果你想要一个随机的Unicodestring,你可以创build随机字节,然后使用有效的字节。

  OSStatus sanityCheck = noErr; uint8_t * randomBytes = NULL; size_t length = 200; // can of course be variable randomBytes = malloc( length * sizeof(uint8_t) ); memset((void *)randomBytes, 0x0, length); sanityCheck = SecRandomCopyBytes(kSecRandomDefault, length, randomBytes); if (sanityCheck != noErr) NSLog(@"Error generating random bytes, OSStatus == %ld.", sanityCheck); NSData* randomData = [[NSData alloc] initWithBytes:(const void *)randomBytes length: length]; if (randomBytes) free(randomBytes); NSString* dataString = [[NSString alloc] initWithCharacters:[randomData bytes] length:[randomData length]]; // create an NSString from the random bytes NSData* tempData = [dataString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; // remove illegal characters from string NSString* randomString = [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding]; 

从NSString转换到NSData和返回是获得有效的UTF-8string所必需的。 请注意,长度不一定是最后创build的NSString的长度。

我用一个简单的char[]而不是NSString *作为字母表。 我将其添加到NSString类别。

 static const char __alphabet[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; + (NSString *)randomString:(int)length { NSMutableString *randomString = [NSMutableString stringWithCapacity:length]; u_int32_t alphabetLength = (u_int32_t)strlen(__alphabet); for (int i = 0; i < length; i++) { [randomString appendFormat:@"%c", __alphabet[arc4random_uniform(alphabetLength)]]; } return randomString; } 
 static NSUInteger length = 32; static NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; NSMutableString * randomString = [NSMutableString stringWithCapacity:length]; for (NSInteger i = 0; i < length; ++i) { [randomString appendFormat: @"%C", [letters characterAtIndex:(NSUInteger)arc4random_uniform((u_int32_t)[letters length])]]; } 

调用方法:


 NSString *string = [self stringWithRandomSuffixForFile:@"file.pdf" withLength:4] 

方法:


 - (NSString *)stringWithRandomSuffixForFile:(NSString *)file withLength:(int)length { NSString *alphabet = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; NSString *fileExtension = [file pathExtension]; NSString *fileName = [file stringByDeletingPathExtension]; NSMutableString *randomString = [NSMutableString stringWithFormat:@"%@_", fileName]; for (int x = 0; x < length; x++) { [randomString appendFormat:@"%C", [alphabet characterAtIndex: arc4random_uniform((int)[alphabet length]) % [alphabet length]]]; } [randomString appendFormat:@".%@", fileExtension]; NSLog(@"## randomString: %@ ##", randomString); return randomString; } 

结果:


 ## randomString: file_Msci.pdf ## ## randomString: file_xshG.pdf ## ## randomString: file_abAD.pdf ## ## randomString: file_HVwV.pdf ## 

为Swift 3.0

 func randomString(_ length: Int) -> String { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let len = UInt32(letters.length) var randomString = "" for _ in 0 ..< length { let rand = arc4random_uniform(len) var nextChar = letters.character(at: Int(rand)) randomString += NSString(characters: &nextChar, length: 1) as String } return randomString } 
 #define ASCII_START_NUMERS 0x30 #define ASCII_END_NUMERS 0x39 #define ASCII_START_LETTERS_A 0x41 #define ASCII_END_LETTERS_Z 0x5A #define ASCII_START_LETTERS_a 0x61 #define ASCII_END_LETTERS_z 0x5A -(NSString *)getRandomString:(int)length { NSMutableString *result = [[NSMutableString alloc]init]; while (result.length != length) { NSMutableData* data = [NSMutableData dataWithLength:1]; SecRandomCopyBytes(kSecRandomDefault, 1, [data mutableBytes]); Byte currentChar = 0; [data getBytes:&currentChar length:1]; NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if (currentChar > ASCII_START_NUMERS && currentChar < ASCII_END_NUMERS) { // 0 to 0 [result appendString:s]; continue; } if (currentChar > ASCII_START_LETTERS_A && currentChar < ASCII_END_LETTERS_Z) { // 0 to 0 [result appendString:s]; continue; } if (currentChar > ASCII_START_LETTERS_a && currentChar < ASCII_END_LETTERS_z) { // 0 to 0 [result appendString:s]; continue; } } return result; }