1

この投稿は、コードよりも理論的なものかもしれません。

simpleテキストテーブル(基本的には文字の配列)を使用し、その値に基づいて文字列内の文字を置き換える(比較的)方法があるかどうか疑問に思いました。

詳しく説明させてください。

この2行のテーブルがあるとしましょう。

table[0x0] = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'};
table[0x1] = new char[] {'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ']', ',', '/', '.', '~', '&'};

各配列には16個のメンバーがあり、16進数で0〜Fです。

文字列「hello」が16進数(68 65 6C 6C 6F)に変換されているとします。これらの16進数を取得し、上の表で定義されている新しい場所にマップします。

したがって、「こんにちは」は次のようになります。

07 04 0B 0B 0E

文字列を配列に簡単に変換できますが、次に何をすべきか悩んでいます。foreachループでうまくいくと思いますが、正確な内容はまだわかりません。

これを行う簡単な方法はありますか?それほど難しいことではないようですが、どうすればいいのかよくわかりません。

助けてくれてありがとう!

4

1 に答える 1

1
static readonly char[] TABLE = {
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
    'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ']', ',', '/', '.', '~', '&',
};

// Make a lookup dictionary of char => index in the table, for speed.
static readonly Dictionary<char, int> s_lookup = TABLE.ToDictionary(
            c => c,                          // Key is the char itself.
            c => Array.IndexOf(TABLE, c));   // Value is the index of that char.

static void Main(string[] args) {

    // The test input string. Note it has no space.
    string str = "hello,world.";

    // For each character in the string, we lookup what its index in the
    // original table was.
    IEnumerable<int> indices = str.Select(c => s_lookup[c]);

    // Print those numbers out, first converting them to two-digit hex values,
    // and then joining them with commas in-between.
    Console.WriteLine(String.Join(",", indices.Select(i => i.ToString("X02"))));
}

出力:

07,04,0B,0B,0E,1B,16,0E,11,0B,03,1D

ルックアップテーブルにない入力文字を指定した場合、すぐには気付かないことに注意してください。 Selectを返しますIEnumerable。これは、使用するときにのみ遅延評価されます。その時点で、入力文字が見つからない場合、ディクショナリ[]呼び出しはexeceptionをスローします。

これをより明確にする1つの方法はToArray()、Selectの後に呼び出すことです。これにより、ではなく、インデックスの配列が得られますIEnumerable。これにより、評価がすぐに実行されます。

int[] indices = str.Select(c => s_lookup[c]).ToArray();

参照:

于 2013-01-15T06:46:19.463 に答える