Split an NSString to access one particular piece

后端 未结 7 1584
轮回少年
轮回少年 2020-11-27 11:59

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?

相关标签:
7条回答
  • 2020-11-27 12:26

    Its working fine

    NSString *dateString = @"10/10/2010";//Date 
    NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
    NSString* dayString = [dateArray objectAtIndex: 0];
    
    0 讨论(0)
  • 2020-11-27 12:27

    Use [myString componentsSeparatedByString:@"/"]

    0 讨论(0)
  • 2020-11-27 12:41
    NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
    NSString* firstBit = [foo objectAtIndex: 0];
    

    Update 7/3/2018:

    Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:

    let substrings = "10/04/2011".split(separator: "/")
    let firstBit = substrings[0]
    

    Although note that it gives you an array of Substring. If you need to convert these back to ordinary strings, use map

    let strings = "10/04/2011".split(separator: "/").map{ String($0) }
    let firstBit = strings[0]
    

    or

    let firstBit = String(substrings[0])
    
    0 讨论(0)
  • 2020-11-27 12:42

    Objective-c:

         NSString *day = [@"10/04/2011" componentsSeparatedByString:@"/"][0];
    

    Swift:

         var day: String = "10/04/2011".componentsSeparatedByString("/")[0]
    
    0 讨论(0)
  • 2020-11-27 12:42

    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];
    }
    
    0 讨论(0)
  • 2020-11-27 12:49

    Swift 3.0 version

    let arr = yourString.components(separatedBy: "/")
    let month = arr[0]
    
    0 讨论(0)
提交回复
热议问题