简体   繁体   English

从字符中拆分字符串

[英]Split string from the character

I am trying to get Numeric from the string.我正在尝试从字符串中获取数字。 I have string with phone number so I need numerics only.我有电话号码的字符串,所以我只需要数字。

My string format is:我的字符串格式是:

P: 000-000-0000电话:000-000-0000
So I am using following code for that:所以我为此使用以下代码:

[[strPhone componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];

In few cases I am getting following format for my string:在少数情况下,我的字符串会采用以下格式:

P: 000 000 0000 M: 000 000 0000电话:000 000 0000 米:000 000 0000

What I want to do is.. I want to split my string in an array.我想做的是..我想将我的字符串拆分成一个数组。 for that purpose I need to split my string from the characters.为此,我需要将字符串与字符分开。

Is there any way to achive this thing.有什么办法可以达到这个目的。

In case that if we have如果我们有

P: 000 000 0000 Mo: 000 000 0000 format then the array should have only two parts. P: 000 000 0000 Mo: 000 000 0000 格式那么数组应该只有两部分。 One should split with "P" and second with "Mo".一个应该与“P”分开,第二个应该与“Mo”分开。 not the three part one with "P", Second "M", third "o".不是带有“P”,第二个“M”,第三个“o”的三个部分。

Plz help me to achive this.请帮助我实现这一目标。

Thanks谢谢

I assume you have a string with some text and a phone number.我假设您有一个带有一些文本和电话号码的字符串。 In this case you can use the NSDataDetector class.在这种情况下,您可以使用 NSDataDetector class。 Like this:像这样:

NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber
                                                              error:&error];

Then get the results array (phone numbers) by:然后通过以下方式获取结果数组(电话号码):

NSArray * phoneNumbers = [detector metchesInString:YOURSTRING options:0 range:NSMakeRange(0, [YOURSTRING length])];

Use following code:使用以下代码:

NSString *list = @"Norman, Stanley, Fletcher"; NSString *list = @"诺曼、斯坦利、弗莱彻"; NSArray *listItems = [list componentsSeparatedByString:@", "]; NSArray *listItems = [list componentsSeparatedByString:@", "];

The listItmes contains all the separated strings. listItmes 包含所有分隔的字符串。

You could split up the data first to detect multiple numbers in one string using您可以先拆分数据以使用以下方法检测一个字符串中的多个数字

NSArray *candidates = [strPhone componentsSeparatedByString:@":"];

Then loop over the candidates and perform your previous phone number check and remove all empty strings from the result, eg然后遍历候选人并执行您之前的电话号码检查并从结果中删除所有空字符串,例如

for (NSString *candidate in candidates) {
    NSString *result = <what you did before>;
    if ([result length] > 0) {
        <add to results array>;
    }
}

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

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