我可以将给定的单词(String)表示为数字吗?

问题描述 投票:0回答:2

假设我有一个单词列表,例如

var words = new [] {"bob", "alice", "john"};

有没有办法将每个单词表示为数字,以便可以使用这些数字对单词进行排序。

我认为可以使用的一个用例是使用Counting Sort来排序单词列表。我再次感兴趣的是,这是否完全不是因为它可能不是排序单词列表的最有效方式。

请注意,这不是关于哈希码或不同的排序算法。我很想知道字符串是否可以表示为数字。

c# .net string character-encoding numbers
2个回答
0
投票

您可以使用字典而不是数组。

public class Program
{
    static void Main(string[] args)
    {
        IDictionary<int, string> words = new Dictionary<int, string>();
        words.Add(0, "bob");
        words.Add(1, "alice");
        words.Add(2, "john");

        foreach (KeyValuePair<int, string> word in words.OrderBy(w => w.Key))
        {
            Console.WriteLine(word.Value);
        }

        Console.ReadLine();
    }
}

注意:对于大多数开发人员来说,使用集合替代数组更好更容易。


0
投票

我不明白下来的选票但嘿,这是我到目前为止所提出的:

private int _alphabetLength = char.MaxValue - char.MinValue;
private BigInteger Convert(string data)
{
    var value = new BigInteger();
    var startPoint = data.Length - 1;
    for (int i = data.Length - 1; i >= 0; i--)
    {
        var character = data[i];
        var charNumericValue = character;
        var exponentialWeight = startPoint - i;
        var weightedValue = new BigInteger(charNumericValue * Math.Pow(_alphabetLength, exponentialWeight));
        value += weightedValue;
    }
    return value;
}

使用以上转换以下内容:

var words = new [] {"bob", "alice", "john" };
  • 420901224533 //鲍勃
  • -9223372036854775808 // alice
  • 29835458486206476 //约翰

尽管溢出输出看起来排序给我,我需要改进它并正确测试它,但至少它是一个开始。

© www.soinside.com 2019 - 2024. All rights reserved.