iOS找到单词索引

时间:2016-09-02 12:05:31

标签: ios objective-c

假设我在UITextView中有一个字符串:

NSString *str = @"Hello world. How @are you ? Hope that @you are @doing well. Can you @please suggest me?" 

这里,在上面的字符串中有4个单词,前缀为“@”。现在我该如何找到计数及其索引?像:

(@are = 0,  @"you" = 1, @"doing" = 2, @"please"=3)

2 个答案:

答案 0 :(得分:1)

获取以@开头的单词数组。数组中的单词索引将是字符串中的索引。

NSString *str = @"Hello world. How @are you ? Hope that @you are @doing well. Can you @please suggest me?";
NSMutableArray *atWordArray = [[NSMutableArray alloc] init];
NSArray *arrAllStr = [str componentsSeparatedByString:@" "];

for (NSString *individualString in arrAllStr) {
    if ([individualString hasPrefix:@"@"]) {
        [atWordArray addObject:individualString];
    }
}

NSLog(@"There are %d word/s in string they are /n",atWordArray.count,atWordArray);

答案 1 :(得分:0)

你可以这样做,

    NSString *str = @"Hello world. How @are you ? Hope that @you are @doing well. Can you @please suggest me?";

NSArray *arr = [str componentsSeparatedByString:@" "];

NSMutableArray *resultArr = [[NSMutableArray alloc]init];
NSMutableArray *resultArr2 = [[NSMutableArray alloc]init];

for (int i = 0; i < arr.count; i++) {


    if ([[[arr objectAtIndex:i] substringToIndex:1] isEqualToString:@"@"]) {

        [resultArr addObject:[arr objectAtIndex:i]];


    }

}

   // NSLog(@"result Arr : %@",resultArr);

for (int j = 0; j < resultArr.count; j++) {



    NSLog(@"%@ = %d",[resultArr objectAtIndex:j],j);
    NSDictionary *temp = [NSDictionary dictionaryWithObject:[resultArr objectAtIndex:j] forKey:[NSString stringWithFormat:@"%d",j]];
    [resultArr2 addObject:temp];
}


NSLog(@"array 2 : %@",resultArr2);