开发者

String index from line index and column index in NSString

开发者 https://www.devze.com 2023-01-11 07:35 出处:网络
Is there any easy way to get the string index in an NSString if I have the line number and column number?

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
开发者_如何学JAVA

[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).


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消