How to convert a string to integer
Example : a = 1 b = 2 c = 3 .. .. z = 26 aa = 27 ab = 28
how to convert another string into an integer? for example i want to convert 'lmao' to an integer. please h开发者_如何学运维elp me :) thank you. in pascal :)
To convert ordinary base-10 strings into numbers, you take each character from left to right, convert it to its numeric value (between 0 and 9) and add it to the total you already have (which you initialize to zero). If there are more characters following the one you just processed, then multiply the total by 10. Repeat until you run out of characters.
For example, the number 374 is 3×102 + 7×101 + 4×100. Another way of writing that, which more closely models the conversion algorithm I described above, is (((3)×10+7)×10+4.
You can adapt that to handle any string of characters, not just numeric characters. Instead of 10, the base is 26, so multiply by that. And instead of digits, the characters are a through z. Your example string would be evaluated like this: (((l)×26+m)×26+a)×26+o. Substitute numbers for those letters, and you get 219,742.
Here's some code to do it. It doesn't check for errors; it assumes that the string will only contain valid characters and that the string won't represent a number that's too big to fit in an Integer variable.
function SpecialStrToInt(const s: string): Integer;
var
i: Integer;
subtotal: Integer;
c: Char;
charval: Integer;
begin
subtotal := 0;
for i := 1 to Length(s) do begin
c := s[i];
charval := Ord(c) - Ord('a') + 1;
subtotal := subtotal * 26;
subtotal := subtotal + charval;
end;
SpecialStrToInt := subtotal;
end;
An oddity about your format is that there's no way to represent zero.
精彩评论