如何从iOS中的字符串中的第三个逗号(,)后删除字符串?

时间:2014-01-08 10:32:35

标签: ios

我从Web服务获取一个字符串,如:     @“当前地址是Narveer Tanaji Malusare Road,Dandekar Pool,Dattavadi,Pune,Maharashtra 411030,India”。     现在我想在第三个逗号后删除字符串,所以地址将如下所示:    @“当前地址是Narveer Tanaji Malusare Road,Dandekar Pool,Dattavadi”;    并删除第三个逗号。    请帮帮我。

谢谢

3 个答案:

答案 0 :(得分:2)

使用componentsSeparatedByString

NSString *list = @"current address is Narveer Tanaji Malusare Road, Dandekar Pool, Dattavadi, Pune, Maharashtra 411030, India";
NSArray *listItems = [list componentsSeparatedByString:@","];

// produces an array { @"Karin", @"Carrie", @"David"" }.

//这里检查listItems.count> = 3

NSString* reducedString = [NSString stringWithFormat:@"%@, %@, %@",[listItems objectAtIndex:0],[listItems objectAtIndex:1],[listItems objectAtIndex:2] ];

答案 1 :(得分:0)

您可以使用基本的NSString方法实现您想要的效果。

我刚刚写了一个方法,它正是你所要求的:

-(NSString *) clearStringAfterThirdComma: (NSString *) originalString {

    NSMutableString *clearedString = [originalString mutableCopy];

    NSInteger commaCount = 0;

    // iterate thru each character of the string

    for (NSInteger i = 0; i < originalString.length; i++) {

        NSString *subString = [originalString substringWithRange:NSMakeRange(i, 1)];

        if ([subString isEqualToString:@","]) {

            commaCount++;

            if (commaCount == 3) {
                [clearedString deleteCharactersInRange:NSMakeRange(i, originalString.length - i)];
                break;
            }
        }
    }

    return clearedString;
}

答案 2 :(得分:0)

我知道这已经得到了解答,但这让我感到困扰,所以这是我的解决方案;

以下是方法:

- (NSString *)shortenedAddress:(NSString *)address {
    // Turn the string into an array of each part separated by a comma
    NSArray *components = [address componentsSeparatedByString:@","];

    // No need to shorten the address if there are three items or less
    if ([components count] < 4) {
        return address;
    }

    // Create a range object for the first three items in the array
    NSRange range;
    range.location = 0;
    range.length = 3;

    return [[components subarrayWithRange:range] componentsJoinedByString:@","];
}

如果你用它测试它:

NSString *fullAddress = @"current address is Narveer Tanaji Malusare Road, Dandekar Pool, Dattavadi, Pune, Maharashtra 411030, India"; // More than three items
NSString *partialAddress = @"current address is Narveer Tanaji Malusare Road, Dandekar Pool"; // Less than three items

NSLog(@"Full Address: %@", [self shortenedAddress:fullAddress]);
NSLog(@"Partial Address: %@", [self shortenedAddress:partialAddress]);

它在控制台中提供以下输出:

  

Full Address: current address is Narveer Tanaji Malusare Road, Dandekar Pool, Dattavadi

     

Partial Address: current address is Narveer Tanaji Malusare Road, Dandekar Pool

我认为它比接受的答案更短,更容易理解,更容易修改,但这只是我的意见。