弄乱NSString的顺序的快速方法?

编程入门 行业动态 更新时间:2024-10-13 12:24:40
本文介绍了弄乱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的顺序的快速方法?

本文发布于:2023-11-30 13:52:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650225.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   快速   方法   NSString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!