如何将字符串转换为整数

发布于 2024-10-02 21:04:17 字数 117 浏览 0 评论 0原文

例子 : 一个= 1 b = 2 c = 3 .. .. z = 26 氨基酸 = 27 ab = 28

如何将另一个字符串转换为整数?例如我想将“lmao”转换为整数。请帮助我:) 谢谢。 帕斯卡:)

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 help me :) thank you.
in pascal :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

两人的回忆 2024-10-09 21:04:17

要将普通的以 10 为基数的字符串转换为数字,您需要从左到右取出每个字符,将其转换为其数值(0 到 9 之间),并将其添加到已有的总数中(初始化为零)。如果您刚刚处理的字符后面还有更多字符,则将总数乘以 10。重复此操作,直到字符用完。

例如,数字 374 是 3×102 + 7×101 + 4×100。另一种写法是 (((3)×10+7)×10+4,它更接近地模拟我上面描述的转换算法。

您可以调整它来处理任何字符串,而不仅仅是数字字符。 10 的基数是 26,因此乘以该数字,字符是 az。您的示例字符串将按如下方式计算:(( (l)×26+m)×26+a)×26+o 替换这些数字。字母,你会得到 219,742。

它不会检查错误;它假设该字符串只包含有效字符,并且该字符串不会代表太大而无法容纳在整数中的数字。变量的

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;

格式的一个奇怪之处是无法表示零。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文