6

Convert a sentence to integer

 2 years ago
source link: https://www.codesd.com/item/convert-a-sentence-to-integer.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Convert a sentence to integer

advertisements

Assuming i have a string that says

string version  = "Version 1.0.2.3"

I want to convert this to an integer or number like "1232454982394". This should change based on the text i input. While one option is to convert to ascii value or unicode, i have to iterate through each character. Wondering if there is an easier way - like a one line method that can accomplish this.

The below one works. but i am looking for something better

string version = "Version 1.0.2.3";
string finalOutput = "";
foreach (char c in version)
{
    finalOutput = finalOutput + ((int)c).ToString();
}

Console.WriteLine(finalOutput);
// Output is 861011141151051111103249464846504651


One way is to use the GetHashCode method.

string version  = "Version 1.0.2.3";
var hashedValue = version.GetHashCode();

From MSDN

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary(Of TKey, TValue) class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK