【问题标题】:Split string by particular character ,iOS [duplicate]按特定字符拆分字符串,iOS [重复]
【发布时间】:2014-07-22 09:15:07
【问题描述】:

我有一个这样构造的字符串:

"Description#Data#IMG"

通过升号位置获得三个不同字符串的最佳方法是什么?

【问题讨论】:

    标签: ios objective-c iphone swift


    【解决方案1】:
    NSString *str=@"Description#Data#IMG";  //is your str
    
    NSArray *items = [str componentsSeparatedByString:@"#"];   //take the one array for split the string
    
    NSString *str1=[items objectAtIndex:0];   //shows Description
    NSString *str2=[items objectAtIndex:1];   //Shows Data
    NSString *str3=[items objectAtIndex:2];   // shows IMG
    
    Finally NSLog(@"your  3 stirs ==%@   %@  %@", str1, str2, str3);
    

    斯威夫特

     //is your str  
     var str: String = "Description#Data#IMG"
    
    let items = String.components(separatedBy: "#") //take the one array for split the string
    var str1: String = items.objectAtIndex(0)    //shows Description
    var str2: String = items.objectAtIndex(1)    //Shows Data
    var str3: String = items.objectAtIndex(2) // shows IMG
    

    选项-2

    let items = str.characters.split("#")
    var str1: String  =  String(items.first!)
    var str1: String  =  String(items.last!)
    

    选项 3

    // An example string separated by commas.
    let line = "apple,peach,kiwi"
    
    // Use components() to split the string.
    // ... Split on comma chars.
    let parts = line.components(separatedBy: ",")
    
    // Result has 3 strings.
    print(parts.count)
    print(parts)
    

    【讨论】:

      【解决方案2】:
      NSArray *components=[@"Description#Data#IMG" componentsSeparatedByString:@"#"];
      

      【讨论】:

        【解决方案3】:

        我会这样做:

        NSString *string = @"Description#Data#IMG";
        
        NSArray *items = [string componentsSeparatedByString:@"#"];
        

        【讨论】:

          猜你喜欢
          • 2015-12-18
          • 1970-01-01
          • 1970-01-01
          • 2020-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-14
          • 2014-01-12
          相关资源
          最近更新 更多