Vikas Maini
Vikas Maini

Reputation: 45

Not getting correct index for the char in String

I have a string like "What is it in rain"

I need to add blink under each character that needs to be typed through keyboard. So I find the character using [characterAtIndex]..

But when I reach to the i in 'it' find the index of i using [characterAtIndex:i], it returns 5. which has to be 8 in the string.

How to get the correct index of next repeated character in a string?

Code:

- (int) getCurrentIndexOfChar : (unichar)c instring : (NSString *)str {
      for (int i = 0; i<=[str.length]; i++) {
         if(c == [str characterAtIndex:i]) {
             if (previousChar == c){    //I check here for previous character 
                  return i+1;           //If the previous character is same as next I increment index
             } else {
                  return i;
             }
             previousChar = c;
          }
      }
}

Upvotes: 3

Views: 137

Answers (1)

βhargavḯ
βhargavḯ

Reputation: 9836

Please try this way

NSString *main = @"This is it in rain";
NSString *search = @"This is i";
NSLog(@"Index: %d",[main rangeOfString:search].location+[search length]-1);

Here you can replace search with the text inputed by user.

Upvotes: 3

Related Questions