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

时间:2016-02-29 07:08:30

标签: ios objective-c iphone string nsstring

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

代码在viewDidLoad中正常工作但在textfield中无法工作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);

}

结果:: a :: 17 @ :: 26 #:: 2147483647 $ :: 20

enter image description here

2 个答案:

答案 0 :(得分:6)

尝试%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);

a :: 17

@ :: 26

#:: 13

$ :: 20

答案 1 :(得分:3)

首先,你有拼写错误。它是[HttpGet, Route("GetListBy")] public async Task<IHttpActionResult> GetListBy([FromUri] PaperAdFilterParameter ipaperAdFilterParameter) { var paperAdList = await _paperAdService.GetListAsync(ipaperAdFilterParameter); if (paperAdList.IsNull()) return NotFound(); return Ok(paperAdList); } ,而不是NSString *str

其余部分在我的机器上运行良好。

NSSting *str

答案:

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

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

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

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

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

你能说得更清楚吗?