按特定字符拆分字符串,iOS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23991392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:15:11 来源:igfitidea点击:
Split string by particular character ,iOS
提问by Istorn
I have a string structured in this way:
我有一个以这种方式构造的字符串:
"Description#Data#IMG"
"Description#Data#IMG"
What's the best method to obtain three distinct strings through the position of sharps?
通过尖锐的位置获得三个不同字符串的最佳方法是什么?
回答by Anbu.Karthik
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);
Swift
迅速
//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
option-2
选项 2
let items = str.characters.split("#")
var str1: String = String(items.first!)
var str1: String = String(items.last!)
option 3
选项 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)
回答by iphonic
NSArray *components=[@"Description#Data#IMG" componentsSeparatedByString:@"#"];
回答by Painted Black
I would do something like this:
我会做这样的事情:
NSString *string = @"Description#Data#IMG";
NSArray *items = [string componentsSeparatedByString:@"#"];