简体   繁体   English

NSString:从逗号分隔的NSString中提取字符串

[英]NSString : String extraction from a comma Separated NSString

Below are two examples of strings separated by comma that I get back as results: 以下是两个用逗号分隔的字符串的示例,我将它们作为结果返回:

NSString *placeResult = @"111 Main Street, Cupertino, CA"

or sometimes the result contains the name of a place: 有时结果中包含地点名称:

NSString *placeResult = @"Starbucks, 222 Main Street, Cupertino, CA"

What's the best way to check the strings above to see if it starts with a name or or a street address? 检查上面的字符串以查看它是否以名称或街道地址开头的最佳方法是什么?

If it does start with a name (ie Starbucks in the 2nd example above"), I'd like to extract the name and store it into another variable. Thus after extraction the string will be: 如果确实以名称开头(即上述第二个示例中的星巴克“),我想提取该名称并将其存储到另一个变量中。因此,提取后的字符串为:

NSLog (@"%s", placeResult);

The log will print: 日志将打印:

"222 Main Street, Cupertino, CA" 

Another string will now store the @"Starbucks" in it: 现在,另一个字符串将在其中存储@“ Starbucks”:

NSLog (@"%s", placeName);

The log will print: 日志将打印:

"Starbucks" 

Important: I can't lose the comma separations after extraction. 重要提示:提取后我不会丢失逗号分隔。

Thank you! 谢谢!

Make use of NSDataDetector and NSTextCheckingResult : 利用NSDataDetectorNSTextCheckingResult

NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeAddress error:nil];
NSString *str = @"Starbucks, 222 Main Street, Cupertino, CA";
NSArray *matches = [detector matchesInString:str options:0 range:NSMakeRange(0, str.length)];
for (NSTextCheckingResult *match in matches) {
    if (match.resultType == NSTextCheckingTypeAddress) {
        NSDictionary *data = [match addressComponents];
        NSLog(@"address = %@, range: %@", data, NSStringFromRange(match.range));

        NSString *name = data[NSTextCheckingNameKey];
        if (!name && match.range.location > 0) {
            name = [str substringToIndex:match.range.location - 1];
            // "name" may now include a trailing comma and space - strip these as needed
        }
    }
}

This outputs: 输出:

address = { 地址= {
City = Cupertino; 城市=库比蒂诺;
State = CA; 状态= CA;
Street = "222 Main Street"; 街道=“ 222大街”;
}, range: {11, 30} },范围:{11,30}

The odd thing is that the resulting dictionary of results does not contain a reference to the "Starbucks" portion. 奇怪的是,结果字典中不包含对“星巴克”部分的引用。 What you can do is check to see of the addressComponents contains a value for the NSTextCheckingNameKey . 你可以做的是检查看到的addressComponents包含了一个值NSTextCheckingNameKey If not, check the range of the match. 如果不是,请检查匹配范围。 If the match's range isn't the start of the string, then you can use that value to extract the name from the beginning of the string. 如果匹配的范围不是字符串的开头,则可以使用该值从字符串的开头提取名称。

To get an array of the things between commas, you could use: 要获取逗号之间的所有内容,可以使用:

NSArray *components = [placeResult componentsSeparatedByString:@","];

Possibly with a follow-up of: 可能会跟进:

NSMutableArray *trimmedComponents =
           [NSMutableArray arrayWithCapacity:[components count]];

NSCharacterSet *whitespaceCharacterSet = [NSCharacterSet whitespaceCharacterSet];

for(NSString *component in components)
    [trimmedComponents addObject:
             [component stringByTrimmingCharactersInSet:whitespaceCharacterSet]];

To remove any leading or trailing spaces from each individual component. 从每个单独的组件中删除任何前导或尾随空格。 You would reverse the transformation using eg 您将使用例如反向转换

NSString *fullAddress = [trimmedComponents componentsJoinedByString:@", "];

So then the question is, given NSString *firstComponent = [trimmedComponents objectAtIndex:0]; 因此,问题是,给定NSString *firstComponent = [trimmedComponents objectAtIndex:0]; , how do you guess whether it is a name or a street address? ,您如何猜测它是名字还是街道地址? If it's as simple as checking whether there's a number at the front that isn't zero then you can just do: 如果只是简单地检查前面是否有一个不为零的数字,那么您可以执行以下操作:

if([firstComponent integerValue])
{
    /* ... started with a non-zero number ... */

    NSString *trimmedAddress = [[trimmedComponents subArrayWithRange:
      NSMakeRange(1, [trimmedComponents count]-1)] componentsJoinedByString:", "];

    NSLog(@"trimmed address is: %@");
}

Though that conditional test would also have worked with placeResult , and you'll probably want to add validity checks to make sure you have at least two components before you start assuming you can make an array from the 2nd one onwards. 尽管该条件测试也可以与placeResult一起使用,并且您可能要添加有效性检查,以确保您至少有两个组件,然后再开始假设可以从第二个开始创建一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM