Wednesday, August 28, 2013

Get Key Value From String

There are times when we need to store a key-value pair string (in a variable, fields, etc.), and then later read back the values from there.

For example, we may store a key-value pair in this format:
[key=value]
For multiple key-value pairs, we could store them in this way:
[key1=value1][key2=value2][key3=value3]

So, to read back the key-value pair string values, we can use the following methods:
/// <summary>
/// Gets value from a key-value pair string. In format [key=value].
/// </summary>
/// <param name="source">The source string to check.</param>
/// <param name="key">The key to find.</param>
/// <returns>The key's value.</returns>
public static string GetKeyValueFromString(string source, string key)
{
    return GetKeyValueFromString(source, key, "[", "]", "=");
}

/// <summary>
/// Gets value from a key-value pair string, in format with the signs provided. E.g. [key=value].
/// </summary>
/// <param name="source">The source string to check.</param>
/// <param name="key">The key to find.</param>
/// <param name="encloseLeftSign">Left enclosure sign.</param>
/// <param name="encloseRightSign">Right enclosure sign.</param>
/// <param name="equalSign">Equal sign.</param>
/// <returns>The key's value.</returns>
public static string GetKeyValueFromString(string source, string key, string encloseLeftSign, string encloseRightSign, string equalSign)
{
    if (String.IsNullOrEmpty(encloseLeftSign) || String.IsNullOrEmpty(encloseRightSign) || String.IsNullOrEmpty(equalSign))
        throw new ArgumentException("encloseLeftSign, encloseRightSign, equalSign arguments cannot be null or empty.");     // Validate signs.

    if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(key))
        return "";

    key = encloseLeftSign + key + equalSign;

    if (source.IndexOf(key) < 0)
        return "";

    string value = "";

    value = source.Substring(source.IndexOf(key) + key.Length);
    value = value.Substring(0, value.IndexOf(encloseRightSign));

    return value;
}

Note:
The first overload reads the value by using the default enclosure and equal signs (as in [key=value]), whereas the second overload reads the value by using the specified enclosures and equal signs (e.g. {key:value}, <key#value>, etc.).


Example:

// Store 3 key-value pairs into a "data" variable.
string data = "[code=3305][name=Peter Ross][url=www.example.com]";

// Read back the key values from the "data" variable.
string code = GetKeyValueFromString(data, "code");    // Value is "3305".
string name = GetKeyValueFromString(data, "name");    // Value is "Peter Ross".
string url  = GetKeyValueFromString(data, "url");     // Value is "www.example.com".



If you find this post helpful, would you buy me a coffee?


No comments:

Post a Comment