2011-02-27 62 views
1

我有NSString's的形式Johnny likes "eating" apples。我想從我的字符串中刪除引號以便。NSScanner從NSString中刪除子串報價

約翰尼喜歡 「吃」 蘋果

成爲

約翰喜歡蘋果

我一直在玩NSScanner這樣的伎倆,但我發現一些崩潰。

- (NSString*)clean:(NSString*) _string 
{ 
    NSString *string = nil; 
    NSScanner *scanner = [NSScanner scannerWithString:_string]; 
    while ([scanner isAtEnd] == NO) 
    { 
     [scanner scanUpToString:@"\"" intoString:&string]; 
     [scanner scanUpToString:@"\"" intoString:nil]; 
     [scanner scanUpToString:@"." intoString:&string]; // picked . becuase it's not in the string, really just want rest of string scanned 
    } 
    return string; 
} 
+0

請發佈您的錯誤/崩潰日誌。 – Dominic 2011-02-27 20:50:46

回答

2

此代碼是hacky,但似乎產生你想要的輸出。
它沒有測試意外的輸入(字符串不在描述的形式,無字符串...),但應該讓你開始。

- (NSString *)stringByStrippingQuottedSubstring:(NSString *) stringToClean 
{ 
    NSString *strippedString, 
      *strippedString2; 

    NSScanner *scanner = [NSScanner scannerWithString:stringToClean]; 

    [scanner scanUpToString:@"\"" intoString:&strippedString];       // Getting first part of the string, up to the first quote 
    [scanner scanUpToString:@"\" " intoString:NULL];         // Scanning without caring about the quoted part of the string, up to the second quote 

    strippedString2 = [[scanner string] substringFromIndex:[scanner scanLocation]];  // Getting remainder of the string 

    // Having to trim the second part of the string 
    // (Cf. doc: "If stopString is present in the receiver, then on return the scan location is set to the beginning of that string.") 
    strippedString2 = [strippedString2 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\" "]]; 

    return [strippedString stringByAppendingString:strippedString2]; 
} 

稍後我會回來的(多)進行清潔,並鑽入類NSScanner的資料推測,我錯過了什麼,而不得不照顧有手動微調的字符串。

+0

這似乎工作得很好。添加了一個檢查,以確保參數不是在路上,我認爲這很好。謝謝! – Ternary 2011-02-28 01:06:13