将字符串(单词)转换为长

我想从“Testcase1”、“Testcase2”等字符串创建一个唯一的 ID。因此,我想将字符串分别转换为整数。


我已经尝试过了,但我认为数字/ID 既不是唯一的,也不是这种方法正确的。我想将整个单词转换为数字。


long numberId = 0;

foreach (var character in testString.ToCharArray())

{

    numberId +=  Convert.ToInt16(character);

}


收到一只叮咚
浏览 83回答 3
3回答

千万里不及你

不确定这是否是您所追求的:static void Main(string[] args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var inputText = "Testcase1";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine($"{inputText} =>{CalculateTotal(GetHashString(string.Concat(inputText,DateTime.Now.Date.ToString(),&nbsp; DateTime.Now.TimeOfDay.ToString())).ToArray<char>())}");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inputText = "Testcase2";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine($"{inputText} =>{CalculateTotal(GetHashString(string.Concat(inputText,DateTime.Now.Date.ToString(),&nbsp; DateTime.Now.TimeOfDay.ToString())).ToArray<char>())}");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; static string GetHashString(string inputText)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HashAlgorithm hash = new SHA256Managed();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var bytes = new byte[inputText.Length];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bytes = Encoding.ASCII.GetBytes(inputText);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Encoding.ASCII.GetString( hash.ComputeHash(bytes));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; static long CalculateTotal(char [] items)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var i = Array.ConvertAll<char, long>(items, Convert.ToInt64);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i.Sum();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }输出:测试用例1 => 1880测试用例2 => 1788

桃花长相依

这个实现如何使用基于测试字符串的字节数组之和:&nbsp; &nbsp; long uniqueId = "Testcase1".SelectMany(BitConverter.GetBytes).ToArray().Sum(c=> c);&nbsp; &nbsp; long uniqueId2 = "Testcase2".SelectMany(BitConverter.GetBytes).ToArray().Sum(c => c);测试用例1 -> 877测试用例2 -> 878

忽然笑

我没有证据,但我认为以下方法会产生独特的价值。public static void Main(){&nbsp; &nbsp; long numberId = 0;&nbsp; &nbsp; var testString = "Testcase3";&nbsp; &nbsp; long multiplier = (long)Math.Pow(10,testString.Length);&nbsp; &nbsp; foreach (var character in testString.ToCharArray())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; numberId +=&nbsp; Convert.ToInt16(character)*multiplier;&nbsp; &nbsp; &nbsp; &nbsp; multiplier /=10;&nbsp; &nbsp; }&nbsp; &nbsp; Console.WriteLine(numberId);}
打开App,查看更多内容
随时随地看视频慕课网APP