按特定字符拆分字符串,iOS

时间:2014-06-02 09:33:50

标签: ios objective-c iphone swift

我有一个以这种方式构建的字符串:

"Description#Data#IMG"

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

3 个答案:

答案 0 :(得分:32)

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)

答案 1 :(得分:3)

NSArray *components=[@"Description#Data#IMG" componentsSeparatedByString:@"#"];

答案 2 :(得分:2)

我会做这样的事情:

NSString *string = @"Description#Data#IMG";

NSArray *items = [string componentsSeparatedByString:@"#"];