Difference between revisions of "Code Snippet: Splitting Key-Value Pairs into Components"

From Coder Merlin
(*Added Python example*)
Line 15: Line 15:
}
}
</syntaxhighlight>
</syntaxhighlight>
== Python ==
<syntaxhighlight lang="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 ==
== Java ==
Line 24: Line 34:
     String key = keyValueArray[0];
     String key = keyValueArray[0];
     String value = keyValueArray[1];
     String value = keyValueArray[1];
     System.out.println("KEY is " + key + " VALUE is " + value);
     System.out.println("KEY is '" + key + "', VALUE is '" + value + "'");
}
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 22:19, 5 December 2019

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

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]

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