Search for the last character index (position) (#) in an NSString

You want to get the index of the last occurrence of #, but the following code works fine for another character, but does not give an ideal result for the specifics "#"

Code Works fine in viewDidLoad, but doesn't work in the shouldChangeCharactersInRange text box.

The 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

+4
source share
2 answers

Try% lu unsigned long instead of% d. His work is thin

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

#:: thirteen

$ :: 20

+4
source

Firstly, you have a spelling mistake. This NSString *str, not 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);

:

2016-02-29 15:19:39.554 StackOverflowDemo[9189:1825956] a :: 17   
2016-02-29 15:19:39.555 StackOverflowDemo[9189:1825956] @ :: 26   
2016-02-29 15:19:39.555 StackOverflowDemo[9189:1825956] # :: 13
2016-02-29 15:19:39.555 StackOverflowDemo[9189:1825956] $ :: 20

?

+2

All Articles