views:

22

answers:

1

Is there any easy way to get the string index in an NSString if I have the line number and column number?

For example:

myString =

abc
def
ghi

[myString getIndexFromLineNumber:2 columnNumber:1] should return the index of h in myString, so in this example it should be 10 (assuming new lines are 1 char long).

+1  A: 

There is no default way to do this, so you're going to have to write a category for NSString. Take a look at NSScanner, it will help you quite a bit.

Tips:

  • Wrap the code in the method in a while (![scanner isAtEnd]) to keep scanning through the string in a loop.

  • Use [scanner scanUpToCharactersFromSet:[NSCharacterSet letterCharacterSet] intoString:NULL] and [scanner scanCharactersFromSet:[NSCharacterSet newlineCharacterSet] intoString:NULL] to skip a line (keep doing this until you've reached the line you want, then read the current line and return a given character).

itaiferber