I have a string like this: @"10/04/2011"
and I want to save only the "10" in another string. How can I do that?
This question is related to
objective-c
swift
string
nsstring
Objective-c:
NSString *day = [@"10/04/2011" componentsSeparatedByString:@"/"][0];
Swift:
var day: String = "10/04/2011".componentsSeparatedByString("/")[0]
Use [myString componentsSeparatedByString:@"/"]
Swift 3.0 version
let arr = yourString.components(separatedBy: "/")
let month = arr[0]
I have formatted the nice solution provided by JeremyP above into a more generic reusable function below:
///Return an ARRAY containing the exploded chunk of strings
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
return [stringToBeExploded componentsSeparatedByString: delimiter];
}
Either of these 2:
NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];
Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.
The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.
Its working fine
NSString *dateString = @"10/10/2010";//Date
NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
NSString* dayString = [dateArray objectAtIndex: 0];
Source: Stackoverflow.com