tech_human
tech_human

Reputation: 7100

Range of first and last character in the string

I have a string as per below:

$ab$c x$yz$

The string would always start with $ and would end with a $ character. I wish to find the range of the start $ and end $.

I tried: NSRange range = [myStr rangeOfString:@"$"];

I get the output as (NSRange) $0 = location=0 for its location so I am assuming that it is just returning the range of first '$' found in the string.

How do I get range of start $ and end $?

What I am exactly trying to do here is I am using the below method:

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

So when I type text as '$' I wish to check if '$' is in between start '$' and end '$'. So I am finding it out using the range. If range of '$' I type is between the range of start '$' and end '$' then do this, else do that.

Upvotes: 2

Views: 2920

Answers (4)

Raon
Raon

Reputation: 1286

There is an option for backward search (NSBackwardsSearch). here you can find the correct range of string:

 NSRange rangeFirst = [myStr rangeOfString:@"$"],rangeLast=[myStr rangeOfString:@"$" options:NSBackwardsSearch];

Upvotes: 4

Brams
Brams

Reputation: 674

I think, what you want is a function like this:

-(BOOL) isRange:(NSRange)range includedIn:(NSString*)fullText {
    //Init fullTextRange
    NSRange fullTextRange = NSMakeRange(0, 0);

    if ([fullText hasPrefix:@"$"] && [fullText hasSuffix:@"$"]) {
        //We have a range of start$ and end$
        fullTextRange.length = [fullText length] - 1;
    }

    //Check if range is included in fullTextRange
    return (NSIntersectionRange(range, fullTextRange).length == range.length);
}

It returns YES when the range of the text is between start'$' and end'$'.

You should then use it like this:

 - (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([self isRange:range includedIn:searchBar.text]) {
        //Do something
    }
    else {
        //Do something else
    }
}

Upvotes: 2

Hot Licks
Hot Licks

Reputation: 47729

  • NSRange rangeOfRest = NSRangeMake for 1 past first $ to end of string
  • NSRange secondDollar = [myStr rangeOfString:@"$" options:0 range:rangeOfRest];

Upvotes: 0

RyanR
RyanR

Reputation: 7758

If all you care about is deciding if the text the user is changing does not contain the first or last character (because as you said, the first and last char will always be a '$') this is quite easy.

if(range.location==0)
  return NO; //first $
if(range.location + range.length == text.length - 1)
  return NO; //last $

//Do whatever in the case you want to allow the edit.

Upvotes: 1

Related Questions