首頁>Program>source

我有一个帶有格式標記的字元串,例如 There are {adults} adults, and {children} children .我有一本以"成人"和"子代"為键的字典,我需要查詢该值並用该值替換巨集.這是完全動態的; 密钥可以是任何东西(因此我無法對 stringByReplacingString进行硬編碼 )。

過去,我只是通過遍歷可變字元串並搜尋字元来做類似的事情.删除我从源字元串中已经搜尋過的內容.看来這正是NSScanner設計的用途,所以我尝試了以下方法:

NSScanner *scanner = [NSScanner scannerWithString:format];
NSString *foundString;
scanner.charactersToBeSkipped = nil;
NSMutableString *formatedResponse = [NSMutableString string];
while ([scanner scanUpToString:@"{" intoString:&foundString]) {
    [formatedResponse appendString:[foundString stringByReplacingOccurrencesOfString:@"{" withString:@""]]; //Formatted string contains everything up to the {
    [scanner scanUpToString:@"}" intoString:&foundString];
    NSString *key = [foundString stringByReplacingOccurrencesOfString:@"}" withString:@""];
    [formatedResponse appendString:[data objectForKey:key]];
}
NSRange range = [format rangeOfString:@"}" options:NSBackwardsSearch];
if (range.location != NSNotFound) {
    [formatedResponse appendString:[format substringFromIndex:range.location + 1]];
}

与此有關的問题是,当我的字元串以" {"開頭時,掃描程式將返迴NO,而不是yES. (這就是文件所說的情况).我会滥用NSScanner吗? 事實,事實   不包含正在搜尋的字元串,因為它的輸出似乎使它几乎無用...

scanUpToString

Can this be easily changed to do what I want, or do I need to re-write using a mutable string and searching for the characters manually?
最新回復
  • 4天前
    1 #

    使用 isAtEnd   確定何時停止.還有, {   和 }   不包含在 scanUpToString:的結果中 ,因此它们將在下一个字元串的開頭,但是不需要在迴圈後追加,因為即使未找到搜尋字元串,掃描程式也会返迴掃描的內容。

    // Prevent scanner from ignoring whitespace between formats. For example, without this, "{a} {b}" and "{a}{b}" and "{a}     
    //{b}" are all equivalent
    [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@""]];
    while(![scanner isAtEnd]) {
        if([scanner scanUpToString:@"{" intoString:&foundString]) {
            [formattedResponse appendString:foundString];
        }
        if(![scanner isAtEnd]) {
            [scanner scanString:@"{" intoString:nil];
            foundString = @""; // scanUpToString doesn't modify foundString if no characters are scanned
            [scanner scanUpToString:@"}" intoString:&foundString];
            [formattedResponse appendString:[data objectForKey:foundString];
            [scanner scanString:@"}"];
        }
    }
    

  • php:在Laravel中使用PUT / DELETE有什麼value?
  • 有没有一種方法可以使用emacs安裝R軟體包?