NSMutableString *str =@"abcdefg123";
我希望将每个字符随机添加到一个新的字符串,如@“f1ad2g3be2”。
答案 0 :(得分:3)
NSMutableString *str1 = [[NSMutableString alloc]initWithString:str];
NSMutableString *str2 = [[NSMutableString alloc] init];
while ([str1 length] > 0) {
int i = arc4random() % [str1 length];
NSRange range = NSMakeRange(i,1);
NSString *sub = [str1 substringWithRange:range];
[str2 appendString:sub];
[str1 replaceOccurrencesOfString:sub withString:@"" options:nil range:range];
}
[str1 release];
str2就是你想要的
答案 1 :(得分:3)
非常简单。首先,您必须将字符拆分为数组才能使用。然后你多次交换字母X,我选择这样做,这样每个角色都会被交换
NSString *str =@"abcdefg123";
int length = str.length;
NSMutableArray *letters = [[NSMutableArray alloc] init];
for (int i = 0; i< length; i++) {
NSString *letter = [NSString stringWithFormat:@"%c", [str characterAtIndex:i]];
[letters addObject:letter];
}
for (int i = 0; i<length; i++) {
int value = arc4random() % (length-1);
NSLog(@"Value is : %i", value);
[letters exchangeObjectAtIndex:i withObjectAtIndex:value];
}
NSString *results = [letters componentsJoinedByString:@""];
NSLog(@"The string before : %@", str);
NSLog(@"This is the string now : %@", results);