Convert NSRange contents to NSString?
Asked Answered
S

2

5

I am working on a Cocoa Mac OSX app, and I am wondering if it is possible to present the contents of an NSRange found by:

NSRange range;
range.location = 4;
range.length = 4;

as an NSString?

e.g. in the example above, if I had a string with contents "abcdefgh", presenting the contents of the above range as a string would give "efgh". Is this possible?

Sideslip answered 29/5, 2012 at 18:51 Comment(0)
C
8

Code:

NSString *string = @"abcdefgh";

NSRange range;
range.location = 4;
range.length = 4;

NSString *subString = [string substringWithRange:range];

NSLog(@"%@",subString);

Output:

efgh
Curcio answered 29/5, 2012 at 18:58 Comment(1)
Thank you so much I had never heard of the substringWithRange method!Sideslip
C
2

Try the method substringWithRange from NSString.

NSString* original = @"abcdefgh";
NSLog(@"Substring: %@", [original substringWithRange:range]);
Couperin answered 29/5, 2012 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.