我是iOS新手,所以如果这是初学者级别的问题,请原谅我。
我有一个字符串“hu_HU匈牙利语:匈牙利语”,我想将它放入像{“hu”,“HU”,“Hungary:Hungarian”}这样的数组中。我将如何解析它以删除空格,然后删除下划线?
答案 0 :(得分:2)
使用NSString的componentsSeparatedByCharactersInSet:方法
答案 1 :(得分:0)
要获得所需效果,您必须将'_'更改为'',反之亦然。然后你可以使用componentsSeparatedByString,如下所示:
NSString *source = @"hu_HU Hungary:Hungarian";
source = [source stringByReplacingOccurrencesOfString:@"_" withString:@" "];
NSArray *components = [source componentsSeparatedByString:@" "];
NSLog(@"%@",components);
答案 2 :(得分:0)
NSString *theStr = @"hu_HU Hungary:Hungarian";
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"_ "]];
//pieces = {"hu", "HU", "Hungary:Hungarian"}
pieces = [theStr componentsSeparatedByCharactersInSet: [[NSCharacterSet alphanumericCharacterSet] invertedSet]];
//pieces = {"hu", "HU", "Hungary", "Hungarian"}
//the motivation for this is a better defined set of non-alphanumeric characters
答案 3 :(得分:0)
你在这里:
NSString *myString = @"hu_HU Hungary:Hungarian";
myString = [myString stringByReplacingOccurrencesOfString:@"_" withString:@" "];
NSArray *myArray = [myString componentsSeparatedByString:@" "];
答案 4 :(得分:0)
所有这些答案都有一个恼人的问题。他们假设这些物品被一个且只有一个空间隔开。
NSString *theStr = @"hu_HU Hungary:Hungarian";
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"_ "]];
//pieces = {"hu", "HU", "Hungary:Hungarian"}
NSString *theStr = @"hu_HU Hungary:Hungarian"; // note extra space
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"_ "]];
//pieces = {"hu", "HU", " ", "Hungary:Hungarian"}