gpt4 book ai didi

ios - 在 NSString 中查找字符(#)的最后一个索引(位置)

转载 作者:可可西里 更新时间:2023-11-01 05:07:59 26 4
gpt4 key购买 nike

想要获取# 的最后一次出现的索引,但是下面的代码对另一个字符工作正常但没有给出特殊性“#”的完美结果

代码在 viewDidLoad 中工作正常,但在文本字段 shouldChangeCharactersInRange 中不工作。

代码:

txtTest.text = @"@ashish @test #vijay $4030 @post";


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSRange range = [textField.text rangeOfString:@"a" options:NSBackwardsSearch];
NSLog(@"a :: %d ",range.location);

range = [str rangeOfString:@"@" options:NSBackwardsSearch];
NSLog(@"@ :: %d ",range.location);

range = [str rangeOfString:@"#" options:NSBackwardsSearch];
NSLog(@"# :: %d",range.location);

range = [str rangeOfString:@"$" options:NSBackwardsSearch];
NSLog(@"$ :: %d\n",range.location);

}

结果::一个::17 @::26 #::2147483647 $::20

enter image description here

最佳答案

尝试使用 %lu unsigned long 而不是 %d 。它工作正常

NSString *str = @"ashish @test #vijay $4030 @post";

NSRange range = [str rangeOfString:@"a" options:NSBackwardsSearch];
NSLog(@"a :: %lu ",(unsigned long)range.location);

range = [str rangeOfString:@"@" options:NSBackwardsSearch];
NSLog(@"@ :: %lu ",(unsigned long)range.location);

range = [str rangeOfString:@"#" options:NSBackwardsSearch];
NSLog(@"# :: %lu",(unsigned long)range.location);

range = [str rangeOfString:@"$" options:NSBackwardsSearch];
NSLog(@"$ :: %lu\n",(unsigned long)range.location);

一个::17

@::26

#::13

$::20

关于ios - 在 NSString 中查找字符(#)的最后一个索引(位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35693737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com