Code Snippet: Splitting Key-Value Pairs into Components

From Coder Merlin
Jump to navigation Jump to search

Splitting Key-Value Pairs into Components[edit]

Swift[edit]

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[edit]

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[edit]

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 + "'");
}


CoderMerlin™ proudly recommends:
HintIcon.png

Your purchase via these links helps keep  Coder Merlin™ 's orbuculum ablaze. As an Amazon Associate we earn from qualifying purchases. Thank you for your support!


Designed with pride in Silicon Valley, CA, USA