2011-08-02 6 views
0

NSString内の文字 'a'の出現のすべてのインデックスを返すメソッドがありますか?ドキュメントを見てみると、そこには何もないようです。だから、NSStringをNSArrayの文字列に分解して反復する必要があるかもしれませんか?NSString内の文字のすべてのインデックスを返す

答えて

0

[NSRegularExpression enumerateMatchesInString:options:range:usingBlock:]を試してください。または実際には、他のNSRegularExpressionマッチングメソッドのいずれか。彼らはNSIndexSetを返さないでしょう - それはNSTextCheckingオブジェクトの配列になりますが、あなたはそれから非常に簡単にインデックスを取得できます。

ここではいくつかの(未テスト!)のサンプルコードです:

NSString* aString = @"Here's a string, that contains some letters a"; 
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"a" options:0 error:NULL]; 
NSArray* matches = [regex matchesInString:aString options:0 range:NSMakeRange(0,[aString length])]; 
for(NSTextCheckingResult* i in matches) { 
    NSRange range = i.range; 
    NSUInteger index = range.location; //the index you were looking for! 
    //do something here 
} 

それはenumerateMatchesInStringを使用するために、実際に、より効率的なのですが、私はあなたがブロックであるか馴染みのかわからないので、私はより一般的に高速列挙を選びましたのNSArrayの。

更新:ブロックを使用した同じコード。ここで

NSString* aString = @"Here's a string, that contains some letters a"; 
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"a"; 
[regex enumerateMatchesInString:aString 
         options:0 
          range:NSMakeRange(0,[aString length]) 
        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { 
    NSRange range = result.range; 
    NSUInteger index = range.location; //the index you were looking for 
    //do work here 

}]; 
+0

心配列countlocに保存されていますか? – adit

+1

これはNSUInteger index = range.locationである必要があります。 NSUIntegerの代わりにindex = result.location;私は正しいですか? – Bharathi

+0

...うん。私の脳を怖がって書いてみましょう。 –

0
NSString *[email protected]"The Quick Brown Fox Brown"; 
    NSMutableArray *countloc=[[NSMutableArray alloc]init]; 
    int temp=0; 
    int len=[full_string length]; 
    for(int i =0;i<[full_string length];i++) 
    { 
      NSRange range=[full_string rangeOfString:@"Brown" options:0 range:NSMakeRange(temp,len-1)]; 
      if(range.location<[full_string length]) 
      [countloc addObject:[NSString stringWithFormat:@"%d",range.location]]; 
      temp=range.location+1; 
      len=[full_string length]-range.location; 
      i=temp; 

    } 

サブブラウンを検索し、ストリングの 場所も同様にブロックでコードを投稿

関連する問題