Tag:Foundation
Article From:https://www.cnblogs.com/CoderHong/p/9062318.html

NSString

OCString and C language string conversion

NSString *str = @"Hello world ! !";
// OCString --> C language stringChar *c = [str UTF8String];/ / C string --> OC language stringChar *c = "Hello world!!";NSString *str = [[NSString alloc] initWithUTF8String:c];

Read a string from a file

// The absolute path of a fileNSString *str1 = [[NSString alloc] initWithContentsOfFile:@ "/Users/apple/Desktop/abc.txt" enCoding:NSUTF8StringEncoding error:nil];/ / resourcesNSURL *url = [NSURL URLWithString:@ "file:///Users/apple/Desktop/abc.txt "];NSString *str2 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

Get the NSRange of the specified content in the string

NSString *str = @"Hello world";
// Get a stringNSRange range = [str rangeOfString:@ "Hello"];

The interception of a string

NSString *str = @"HelloWorld";

// Specify index to start intercepting strings (including index)NSString *str2 = [str substringFromIndex:2];/ / start from the beginning of the string to intercept to index (excluding index).)NSString *str2 = [str substringToIndex:3];/ / starts with index and contains index string of length length.NSString *str2 = [stR substringWithRange:NSMakeRange (2, 2)];/ / intercepts all the contents from the string after the known character.NSString *str = @ @ "wechat://router";NSRange chemeRange = [str rangeOfString: @ @ wechat://];NSString *str2 = [str substringFromIndex:cheMeRange.location + chemeRange.length];NSLog (@ @ \nstr2 =% @, STR2); / / output result: router

Leave a Reply

Your email address will not be published. Required fields are marked *