弄乱NSString的顺序的快速方法? [英] Quick way to jumble the order of an NSString?
问题描述
有人知道改变现有NSString或NSMutableString字符顺序的现有方法吗?无论如何,我都有一个解决方法,但是如果有一种现有的方法,那将是很好的.
Does anyone know of an existing way to change the order of an existing NSString or NSMutableString's characters? I have a workaround in mind anyway but it would be great if there was an existing method for it.
例如,给定字符串@"HORSE",该方法将返回@"ORSEH",@"SORHE",@"ROHES"等吗?
For example, given the string @"HORSE", a method which would return @"ORSEH", @"SORHE", @"ROHES", etc?
推荐答案
请考虑以下代码:
.h文件:
Consider this code:
.h File:
@interface NSString (Scrambling)
+ (NSString *)scrambleString:(NSString *)toScramble;
@end
.m文件:
@implementation NSString (Scrambling)
+ (NSString *)scrambleString:(NSString *)toScramble {
for (int i = 0; i < [toScramble length] * 15; i ++) {
int pos = arc4random() % [toScramble length];
int pos2 = arc4random() % ([toScramble length] - 1);
char ch = [toScramble characterAtIndex:pos];
NSString *before = [toScramble substringToIndex:pos];
NSString *after = [toScramble substringFromIndex:pos + 1];
NSString *temp = [before stringByAppendingString:after];
before = [temp substringToIndex:pos2];
after = [temp substringFromIndex:pos2];
toScramble = [before stringByAppendingFormat:@"%c%@", ch, after];
}
return toScramble;
}
@end
不是最漂亮的代码或执行,但是可以完成工作.可能有一种(const char *)方式,但这对我来说很好.快速测试显示在Mac上执行的时间为0.001021秒.
Not the most beautiful code or execution, but gets the job done. There's probably a (const char *) way to do this, but this works fine for me. A quick test shows a 0.001021 second length for execution on my Mac.
用法:
NSString *scrambled = [NSString scrambleString:otherString];
从另一种语言/伪代码改编的代码
Code adapted from another language / pseudocode
这篇关于弄乱NSString的顺序的快速方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!