Jac*_*nkr 3 substring nsstring ios
我试了一个,substringFromIndex:-4但得到了一个错误.如何剪切并保持字符串的结尾?或者说,substr从最后?
例如.
12/12/2012 -> 2012
Run Code Online (Sandbox Code Playgroud)
你必须自己计算,我害怕.这将有效:
NSString *theWholeString = @"12/12/2012";
NSString *substring = [theWholeString substringFromIndex:[theWholeString length] - 4];
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,您也可以使用拆分来执行此操作,如下所示:
NSString *theWholeString = @"12/12/2012";
NSArray *components = [theWholeString componentsSeparatedByString:@"/"];
NSString *substring = [components objectAtIndex:2]; // the third item in the array
Run Code Online (Sandbox Code Playgroud)
如果你想一个接一个地提取日期的每个部分,这可能会更容易.
为了完整起见,如果您要解析日期,最好的方法是使用NSDateFormatter,如下所示:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//first get the date object
[formatter setDateFormat:@"dd/MM/yyyy"]; // make sure you get dd and MM the right way round if you're American
NSDate *date = [formatter dateFromString:@"12/12/2012"];
//now output the part you wanted
[formatter setDateFormat:@"yyyy"];
NSString *justTheYear = [formatter stringFromDate:date];
Run Code Online (Sandbox Code Playgroud)
如果你只想要一年,那就太过分了,但是如果你开始尝试砍掉更复杂的日期/时间字符串,那就更灵活了.
尝试:
NSString *dateString = @"12/12/2012";
NSLog(@"%@", [dateString substringFromIndex:[dateString length]-4]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5452 次 |
| 最近记录: |