Difference between revisions of "Code Snippet: Splitting Key-Value Pairs into Components"
From Coder Merlin
m (*Formatting fixed for real*) |
|||
(2 intermediate revisions by the same user not shown) | |||
Line 14: | Line 14: | ||
print("KEY is '\(key)', VALUE is '\(value)'") | print("KEY is '\(key)', VALUE is '\(value)'") | ||
} | } | ||
</syntaxhighlight> | |||
== Python == | |||
<syntaxhighlight lang="python3"> | |||
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}\'') | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 24: | Line 36: | ||
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> |
Latest revision as of 22:22, 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]
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 + "'");
}