从NSString中分隔单词,其前面是主题标签

时间:2013-04-29 11:54:43

标签: iphone ios objective-c xcode nsstring

我有一个NSString,例如:

"Had a #great time at the #party last night."

我想把它分成一个数组,如下:

"Had a "
"#great"
" time at the "
"#party"
" last night."

我怎么能这样做?

9 个答案:

答案 0 :(得分:4)

NSString *str = @"Had a #great time at the #party last night.";

NSMutableArray *arr = [[NSMutableArray alloc] init];
NSArray *array = [str componentsSeparatedByString:@"#"];
 NSMutableString *retStr= [[NSMutableString alloc] initWithString:[array objectAtIndex:0]];
[arr addObject:retStr];
for(int i=1 ; i<[array count];i++)
{
    NSArray *array1 = [[array objectAtIndex:i] componentsSeparatedByString:@" "];
    {
        NSMutableString *retStr= [[NSMutableString alloc]init];
        for (int i = 0;i< [array1 count]; i++)
        {
            if(i==0)
            {
                [retStr appendFormat:@" #%@ ",[array1 objectAtIndex:i]];
                [arr addObject:retStr];
                retStr= [[NSMutableString alloc]init];
            }
            else
            {
                [retStr appendFormat:@"%@ ",[array1 objectAtIndex:i]];
            }
        }
        [arr addObject:retStr];
    }
}
NSLog(@"%@",arr); 

您可以根据需要获得正确的输出

答案 1 :(得分:3)

尝试这样它会帮助你,

 NSString *str=@"how are #you #friend";
    NSArray *arr=[str componentsSeparatedByString:@" "];
    NSPredicate *p = [NSPredicate predicateWithFormat:@"not SELF contains '#'"];
    NSArray *b = [arr filteredArrayUsingPredicate:p];
    NSLog(@"%@",b);

上面的谓词将返回不包含'#'符号的单词

NSPredicate *p = [NSPredicate predicateWithFormat:@"not SELF like '#*'"];

它会返回不以字母'#'开头的单词

O / P: -

(
    how,
    are
)

EDIT:-

NSString *str=@"how are #you #friend";
    NSArray *arr=[str componentsSeparatedByString:@"#"];
    NSMutableArray *result=[[NSMutableArray alloc]initWithObjects:[arr objectAtIndex:0], nil];
    for(int i=1;i<[arr count];i++){
        [result addObject:[NSString stringWithFormat:@"#%@",[arr objectAtIndex:i]]];
    }
    NSLog(@"%@",result);

O / P: -

(
    "how are ",
    "#you ",
    "#friend"
)

答案 2 :(得分:1)

如果你想在字符串的单个传递中有效地执行它,你可以尝试类似的东西(刮擦代码 - 测试错误/边界情况等等):

int main (int argc, const char * argv[])
{
    NSString *msg = @"Had a #great time at the #party last night.";

    Boolean inTag = NO;
    NSMutableArray *segments = [[NSMutableArray alloc] init];
    NSUInteger idx = 0;
    NSUInteger i=0;
    for (; i < [msg length]; i++)
    {
        unichar ch = [msg characterAtIndex:i];

        if (inTag && ch == ' ')
        {
            [segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
            idx = i;
            inTag = NO;
        }

        if (ch == '#')
        {
            [segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx)]];
            idx = i;
            inTag = YES;
        }
    }

    if (i > idx)
    {
        [segments addObject:[msg substringWithRange:NSMakeRange(idx, i - idx - 1)]];
    }

    for(NSString *seg in segments)
    {
        NSLog(@"%@", seg);
    }
}

输出:

2013-04-29 08:34:34.984 Craplet[95591:707] Had a 
2013-04-29 08:34:34.986 Craplet[95591:707] #great
2013-04-29 08:34:34.986 Craplet[95591:707]  time at the 
2013-04-29 08:34:34.987 Craplet[95591:707] #party
2013-04-29 08:34:34.987 Craplet[95591:707]  last night

答案 3 :(得分:1)

尝试使用此正则表达式:(#.+?\\b)|(.+?(?=#|$))

它找到以hashtag和子序列开头的单词,以hashtag

结尾
NSString * string = @"Had a #great time at the #party last night.";
NSError * error = nil;

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"((#.+?\\b)|(.+?(?=#|$)))"
                                                                       options:0
                                                                         error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult* match in matches ) {
    NSLog(@"%@", [string substringWithRange:[match range]]);
}

输出:

2013-04-29 16:57:51.688 Had a 
2013-04-29 16:57:51.689 #great
2013-04-29 16:57:51.690  time at the 
2013-04-29 16:57:51.691 #party
2013-04-29 16:57:51.692  last night.

答案 4 :(得分:0)

试试这个:

    for (int i=0;i<[YourArray count];i++) {
        NSString *  mystr=[YourArray objectAtIndex:i];
            NSString *temp=[mystr substringToIndex:1];
        if (![temp isEqualToString:@"#"]) {
           //add your string in new array and use this arry.....
        }
    }

答案 5 :(得分:0)

试试这段代码

for (int i=0;i<[YourArray count];i++) {
        NSString *  str=[YourArray objectAtIndex:i];
            NSString *myString=[str substringToIndex:1];
NSString *stringfinal = [myString 
   stringByReplacingOccurrencesOfString:@"#" withString:@""];

    }

答案 6 :(得分:0)

尝试

NSString *string = @"Had a #great time at the #party last night.";
NSArray *components = [string componentsSeparatedByString:@" "];

NSMutableArray *formattedArray = [NSMutableArray array];
NSMutableString *mutableString = [NSMutableString string];
for (NSString *string in components)
{
    if (![string hasPrefix:@"#"]){
        if (!mutableString){
            mutableString = [NSMutableString string];
        }
        [mutableString appendFormat:@" %@",string];
    }else{
        if (mutableString) {
            [formattedArray addObject:mutableString];
            mutableString = nil;
        }
        [formattedArray addObject:string];
    }
}

if (mutableString) {
    [formattedArray addObject:mutableString];
}

NSLog(@"%@",formattedArray);

编辑:

(
    " Had a",
    "#great",
    " time at the",
    "#party",
    " last night."
)

答案 7 :(得分:0)

尝试使用正则表达式。使用此代码,您将能够提取主题标签:

NSString * string = @"Had a #great time at the #party last night.";
NSError * error = nil;

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"((?:#){1}[\\w\\d]{1,140})" options:0 error:&error];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for ( NSTextCheckingResult* match in matches )
{
    NSString * hashtag = [string substringWithRange:[match range]];
    NSLog(@"match: %@", hashtag);
}

有了这个,你就可以建立你正在寻找的数组结果。

答案 8 :(得分:0)

NSScanner

的一次通过解决方案
NSString *string = @"Had a #great time at the #party last night.";
NSMutableArray *array = [@[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];
while (![scanner isAtEnd]) {
    NSString *s;

    [scanner scanUpToString:@"#" intoString:&s];
    if(s) [array addObject:s];
    s = nil;

    [scanner scanUpToString:@" " intoString:&s];
    if(s) [array addObject:s];        
}

结果:

(
    "Had a ",
    "#great",
    "time at the ",
    "#party",
    "last night."
)

如果要保留前导空格,请稍微改为

NSString *string = @"Had a #great time at the #party last night.";
NSMutableArray *array = [@[] mutableCopy];
NSScanner *scanner = [NSScanner scannerWithString:string];

BOOL firstSegment = YES;
while (![scanner isAtEnd]) {
    NSString *s;
    [scanner scanUpToString:@"#" intoString:&s];
    if(s) [array addObject: (!firstSegment) ? [@" " stringByAppendingString:s] : s];
    s = nil;

    [scanner scanUpToString:@" " intoString:&s];
    if(s) [array addObject:s];
    firstSegment = NO;
}

结果:

(
    "Had a ",
    "#great",
    " time at the ",
    "#party",
    " last night."
)