Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way to jumble the order of an NSString?

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.

For example, given the string @"HORSE", a method which would return @"ORSEH", @"SORHE", @"ROHES", etc?

like image 770
Bob-ob Avatar asked Nov 26 '25 19:11

Bob-ob


1 Answers

Consider this code:
.h File:

@interface NSString (Scrambling)

+ (NSString *)scrambleString:(NSString *)toScramble;

@end

.m File:

@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

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.

Usage:

NSString *scrambled = [NSString scrambleString:otherString];

Code adapted from another language / pseudocode

like image 192
Glenn Smith Avatar answered Nov 29 '25 15:11

Glenn Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!