2

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.

4

4 に答える 4

4

後方検索 ( ) のオプションがありますNSBackwardsSearch。ここで、文字列の正しい範囲を見つけることができます:

 NSRange rangeFirst = [myStr rangeOfString:@"$"],rangeLast=[myStr rangeOfString:@"$" options:NSBackwardsSearch];
于 2013-10-17T08:11:54.743 に答える
2

あなたが望むのは次のような関数だと思います:

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

テキストの範囲が start'$' と end'$' の間にある場合、YESを返します。

次に、次のように使用する必要があります。

 - (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([self isRange:range includedIn:searchBar.text]) {
        //Do something
    }
    else {
        //Do something else
    }
}
于 2013-10-16T17:21:25.063 に答える
1

ユーザーが変更しているテキストに最初または最後の文字が含まれていないかどうかを判断するだけであれば (あなたが言ったように、最初と最後の文字は常に '$' になるため)、これは非常に簡単です。

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.
于 2013-10-16T15:46:15.710 に答える
0
  • NSRange rangeOfRest = NSRangeMake for 1 past first $to end of string
  • NSRange secondDollar = [myStr rangeOfString:@"$" options:0 range:rangeOfRest];
于 2013-10-16T20:11:44.103 に答える