Ying
Ying

Reputation: 536

Are there methods to convert between any string and a valid variable name in c#

I need such methods to save some information (for example, formulas) in a variable name.

Of course, it is easy to convert any string to a valid name. But I have 2 unique requirements:

1.The conversion can happen in both directions and after 2 times conversion, we should get the same original string.

Say, convert2OriginalString(Convert2Variable(originalstring)) should always equal to originalstring.

  1. The generated variable name should be readable, not just ugly numbers.

Thank you in advance,

Upvotes: 3

Views: 449

Answers (1)

ste-fu
ste-fu

Reputation: 7482

Just about the only "special" character that is allowed for variable names is the underscore "_"

You could create a custom Dictionary with all of the characters you want to escape, and then iterate through it replacing "special" characters in your string with escaped characters:

    private static string ConvertToSafeName(string input)
    {
        var output = input;

        foreach (var lookup in GetLookups())
        {
            output = output.Replace(lookup.Key, lookup.Value);
        }

        return output;
    }

    private static string RevertToSpecialName(string input)
    {
        var output = input;

        foreach (var lookup in GetLookups())
        {
            output = output.Replace(lookup.Value, lookup.Key);
        }

        return output;
    }

    private static Dictionary<string, string> GetLookups()
    {

        Dictionary<string, string> lookups = new Dictionary<string, string>();
        lookups.Add("=", "_eq_");
        lookups.Add(">", "_gt_");
        lookups.Add("-", "_mn_");
        lookups.Add(" ", "__"); // double underscore for space

        return lookups;
    }

It's not 100% foolproof, but "x=y-z" translates to "x_eq_y_mn_z" and converts back again, and is fairly human readable

Upvotes: 1

Related Questions