Code Snippet: Splitting Key-Value Pairs into Components

From Coder Merlin™

Splitting Key-Value Pairs into Components

Swift

import Foundation

let delimiter = ":"
let keyValueString = "this is my key:this is my value"
let keyValueArray = keyValueString.components(separatedBy:delimiter)

if keyValueArray.count == 2 {
    let key = keyValueArray[0]
    let value = keyValueArray[1]
    print("KEY is '\(key)', VALUE is '\(value)'")
}

Python

delimiter = ':'
keyValueString = 'this is my key:this is my value'
keyValueArray = keyValueString.split(delimiter)

if len(keyValueArray) == 2:
    key = keyValueArray[0]
    value = keyValueArray[1]
    print(f'KEY is \'{key}\', VALUE is \'{value}\'')

Java

String delimiter = ":";
String keyValueString = "this is my key:this is my value";
String[] keyValueArray = keyValueString.split(delimiter);
if (keyValueArray.length == 2) {
    String key = keyValueArray[0];
    String value = keyValueArray[1];
    System.out.println("KEY is '" + key + "', VALUE is '" + value + "'");
}