Shuffling Letters in an NSString in Objective-C

我的未来我决定 提交于 2019-12-03 14:17:21

It would be better to copy the contents of the string into a temporary buffer of type unichar and shuffle the contents of the buffer, instead of creating lots of little strings.

NSUInteger length = [finalLettersString length];

if (!length) return; // nothing to shuffle    

unichar *buffer = calloc(length, sizeof (unichar));

[finalLettersString getCharacters:buffer range:NSMakeRange(0, length)];

for(int i = length - 1; i >= 0; i--){
    int j = arc4random() % (i + 1);
    //NSLog(@"%d %d", i, j);
    //swap at positions i and j
    unichar c = buffer[i];
    buffer[i] = buffer[j];
    buffer[j] = c;
}

NSString *result = [NSString stringWithCharacters:buffer length:length];
free(buffer);

// caution, autoreleased. Allocate explicitly above or retain below to
// keep the string.
finalLettersString = result;

A couple of things you'll have to watch out for:

  1. Unicode strings can contain composite characters and surrogate pairs. Shuffling these around will most likely result in an invalid string. While surrogate pairs are rare, it is not uncommon to find that the character é is composed of two characters (the base lowercase letter e and the combining acute accent).

  2. For large strings it could cause memory problems because you end up using 3 times as much space as the original string (1× for the original string, 2× for the buffer we use, and 3× for the new string, and then back down to 2× once we free the buffer).

A variant of @dreamlax's code that doesn't use char array. Not as efficient for sure. But it doesn't have the Unicode issue.

NSMutableString *randomizedText = [NSMutableString stringWithString:currentText];

NSString *buffer;
for (NSInteger i = randomizedText.length - 1, j; i >= 0; i--)
{
    j = arc4random() % (i + 1);

    buffer = [randomizedText substringWithRange:NSMakeRange(i, 1)];
    [randomizedText replaceCharactersInRange:NSMakeRange(i, 1) withString:[randomizedText substringWithRange:NSMakeRange(j, 1)]];
    [randomizedText replaceCharactersInRange:NSMakeRange(j, 1) withString:buffer];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!