开发者

Getting the wrong string from components separatedByString method

开发者 https://www.devze.com 2023-02-17 20:36 出处:网络
I am using the following code to get the title of a string. Everything works up to the line where I get return [s2 objectAtIndex:0]. The problem is that it is just removing the \"&\" from 开发者_S

I am using the following code to get the title of a string. Everything works up to the line where I get return [s2 objectAtIndex:0]. The problem is that it is just removing the "&" from 开发者_StackOverflow社区the string instead of getting the string in front of the "&". For example:

I am trying to get the title from the string "Sweat (David Guetta Remix) - Snoop Dogg & David Guetta". The method would return "Sweat David Guetta" rather than "Sweat". If you can see the problem please point it out, as it will be of much help!

- (NSString *)getTitleFromString:(NSString *)string {
    NSString *newSongName = [NSString stringWithString:string];
    NSArray *chunks = [newSongName componentsSeparatedByString:@"-"];
    NSString *chunks2s = [chunks objectAtIndex:0];
    NSArray *chunks2 = [chunks2s componentsSeparatedByString:@"("];
    NSString *s = [chunks2 objectAtIndex:0];
    NSArray *s2 = [s componentsSeparatedByString:@"&"];
    return [s2 objectAtIndex:0];
}

Edit----- Finalized Code:

- (NSString *)getTitleFromString:(NSString *)string {
    NSArray * a = [string componentsSeparatedByString:@"-"];
    NSString *b = [a objectAtIndex:0];
    NSArray *c = [b componentsSeparatedByString:@"("];
    NSString *d = [c objectAtIndex:0];
    NSArray *e = [d componentsSeparatedByString:@"&"];
    if ([e count] > 2) {
        return [e objectAtIndex:0];
    } 
    else {
        return d;
    }
    return @"";
}


Given the initial starting string "Sweat (David Guetta Remix) - Snoop Dogg & David Guetta":

  • chunks will be ["Sweat (David Guetta Remix) ", " Snoop Dogg & David Guetta"] (the string split at the "-")

  • chunks2s will be "Sweat (David Guetta Remix) " (the first element of chunks)

  • chunks2 will be "["Sweat ", "David Guetta Remix) "]" (that string split at the opening paren)

  • s will thus be "Sweat " (the first element of chunks2)

And s2 will be the same thing as s, so the method should be returning the correct thing. If it is not, then one of your assumptions is wrong.

0

精彩评论

暂无评论...
验证码 换一张
取 消