簡體   English   中英

將帶有冒號的NSString解析為NSDictionary

[英]Parse NSString with colons into NSDictionary

我正在嘗試解析一個具有以下格式的字符串

Key: Object\n
Key: Object\n
Key: Object\n

進入NSDictionary,以便我可以更輕松地訪問它。 我的問題是:有沒有更好的方法可以將其合並到obj-c中呢? 我的第一個想法是基於:和換行符的分隔來形成一個數組,然后將偶數值用作鍵,將奇數值用作對象,但這似乎有些復雜。

NSString *str = @"Key1: Object1\nKey2: Object2\nKey3: Object3\n";
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSArray *lines = [str componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *aKeyValue in lines)
{
    NSArray *components = [aKeyValue componentsSeparatedByString:@":"];
    if ([components count] != 2) continue; //Bypass stranges lines, like the last one
    NSString *key = [components[0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *value = [components[1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [dict setObject:value forKey:key];
}

NSLog(@"Dict:\n%@", dict);

這給出:

$> Dict:
{
    Key1 = Object1;
    Key2 = Object2;
    Key3 = Object3;
}

注意:我必須使用不同的鍵來重命名您的String,因為它們需要唯一(否則,它將替換僅保留最后一個鍵的值)。 如果不是這種情況,您可能不想要NSDictionary

這段代碼應該可以工作(在Swift中):

func parseString(_ str: String) -> Dictionary<String, String> {
    let lines = str.components(separatedBy: .newlines)
    var dict = [String: String]()
    for line in lines {
        let list = line.components(separatedBy: ": ")
        if list.count == 2 {
            dict[list[0]] = list[1]
        }
    }
    return dict
}

首先,我們用行創建一個數組,然后為每行提取由冒號分隔的鍵和值。

撰寫本文時提供的所有解決方案都會創建一行行,然后處理這些行。 NSString提供方法enumerateLinesUsingBlock:以避免創建此中間的行數組。 假設您的字符串被變量str引用,則:

NSMutableDictionary *results = [NSMutableDictionary new];
[str enumerateLinesUsingBlock:^(NSString *line, BOOL *stop)
{
   NSArray<NSString *> *kvPair = [line componentsSeparatedByString:@":"]; // split key & value
   if (kvPair.count != 2) return; // ignore any line not matching "key : value"
   NSString *key = [kvPair[0] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; // remove any whitespace
   NSString *value = [kvPair[1] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
   results[key] = value;
}];

將在results生成字典。

注意:傳遞給該塊的stop參數是為了允許行枚舉盡早終止,此示例中未使用它。 但是,如果發現格式錯誤的行,則可以將其用於提前終止解析。

使用目標C並沒有更好的方法。這是解決問題的方法。 用換行符分隔字符串,然后再次用“:”分隔每個行字符串,將左部分放在鍵上,右部分放在值上。

NSString *string = @"name: Jack Johnson\n\
                     address: Australia\n\
                     interest: Singing\n\";

NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSArray *keyValuePairs = [trimmedString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

NSMutableDictionary *dict  = [NSMutableDictionary dictionary];

for (NSString *keyValuePair in keyValuePairs) {
    NSArray *keyValues = [keyValuePair componentsSeparatedByString:@":"];

    dict[[keyValues.firstObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]] = [keyValues.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

NSLog(@"%@", dict);

這樣的事情。 但這很快就變得不錯了,

let keyValueTuple = string.trimmingCharacters(in: .whitespacesAndNewlines)
                            .components(separatedBy: .newlines)
                            .map { line -> (String, String) in
                                let keyValuePairs = line.components(separatedBy: CharacterSet(charactersIn: ":"))
                                let key = keyValuePairs.first!.trimmingCharacters(in: .whitespaces)
                                let value = keyValuePairs.last!.trimmingCharacters(in: .whitespaces)
                                return (key, value)
                                }
let dict = Dictionary(uniqueKeysWithValues: keyValueTuple)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM