Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding last Index(position) of the character(#) in NSString

Want to get index of the last occurrence of # but bellow code working fine for the other character but not giving perfect result for particularity "#"

Code Working fine in viewDidLoad but not working in textfield shouldChangeCharactersInRange.

Code:

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);

}

Result :: a :: 17 @ :: 26 # :: 2147483647 $ :: 20

enter image description here

like image 651
Ashish Thummar Avatar asked Dec 24 '22 08:12

Ashish Thummar


1 Answers

Try %lu unsigned long instead of %d . Its working fine

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

like image 154
MOHAMMAD ISHAQ Avatar answered Dec 28 '22 09:12

MOHAMMAD ISHAQ