反转 NSString 文本 [英] Reverse NSString text

查看:27
本文介绍了反转 NSString 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在谷歌上搜索如何做到这一点,但我如何反转 NSString?例如:hi 会变成:ih

I have been googling so much on how to do this, but how would I reverse a NSString? Ex:hi would become: ih

我正在寻找最简单的方法来做到这一点.

I am looking for the easiest way to do this.

谢谢!

@Vince 我做了这个方法:

@Vince I made this method:

- (IBAction)doneKeyboard {

// first retrieve the text of textField1
NSString *myString = field1.text;
NSMutableString *reversedString = [NSMutableString string];
NSUInteger charIndex = 0;
while(myString && charIndex < [myString length]) {
    NSRange subStrRange = NSMakeRange(charIndex, 1);
    [reversedString appendString:[myString substringWithRange:subStrRange]];
    charIndex++;
}
// reversedString is reversed, or empty if myString was nil
field2.text = reversedString;
}

我将该方法连接到 textfield1 的 didendonexit.当我单击完成按钮时,它不会反转文本,UILabel 仅显示我输入的 UITextField 文本.怎么了?

I hooked up that method to textfield1's didendonexit. When I click the done button, it doesn't reverse the text, the UILabel just shows the UITextField's text that I entered. What is wrong?

推荐答案

编写一个简单的循环来做到这一点:

Write a simple loop to do that:

// myString is "hi"
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [myString length];
while (charIndex > 0) {
    charIndex--;
    NSRange subStrRange = NSMakeRange(charIndex, 1);
    [reversedString appendString:[myString substringWithRange:subStrRange]];
}
NSLog(@"%@", reversedString); // outputs "ih"

就您而言:

// first retrieve the text of textField1
NSString *myString = textField1.text;
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [myString length];
while (myString && charIndex > 0) {
    charIndex--;
    NSRange subStrRange = NSMakeRange(charIndex, 1);
    [reversedString appendString:[myString substringWithRange:subStrRange]];
}
// reversedString is reversed, or empty if myString was nil
textField2.text = reversedString;

这篇关于反转 NSString 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆