Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSRange contents to NSString?

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?

like image 586
Conor Taylor Avatar asked May 29 '12 18:05

Conor Taylor


People also ask

What is a NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

What is NSString in objective C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

What is Nsrange?

A structure used to describe a portion of a series, such as characters in a string or objects in an array.


2 Answers

Code:

NSString *string = @"abcdefgh";

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

NSString *subString = [string substringWithRange:range];

NSLog(@"%@",subString);

Output:

efgh
like image 131
Liam George Betsworth Avatar answered Oct 31 '22 15:10

Liam George Betsworth


Try the method substringWithRange from NSString.

NSString* original = @"abcdefgh";
NSLog(@"Substring: %@", [original substringWithRange:range]);
like image 45
J_D Avatar answered Oct 31 '22 16:10

J_D