C++ 字母转数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21832886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting letters to numbers in C++
提问by Michael
PROBLEM SOLVED: thanks everyone!
问题已解决:谢谢大家!
I am almost entirely new to C++ so I apologise in advance if the question seems trivial.
我对 C++ 几乎完全陌生,所以如果问题看起来微不足道,我提前道歉。
I am trying to convert a string of letters to a set of 2 digit numbers where a = 10, b = 11, ..., Y = 34, Z = 35 so that (for example) "abc def" goes to "101112131415". How would I go about doing this? Any help would really be appreciated. Also, I don't mind whether capitalization results in the same number or a different number. Thank you very much in advance. I probably won't need it for a few days but if anyone is feeling particularly nice how would I go about reversing this process? i.e. "101112131415" --> "abcdef" Thanks.
我正在尝试将一串字母转换为一组 2 位数字,其中 a = 10, b = 11, ..., Y = 34, Z = 35 以便(例如)“abc def”变为“101112131415 ”。我该怎么做呢?任何帮助将不胜感激。另外,我不介意大小写是相同的数字还是不同的数字。非常感谢您提前。我可能几天都不需要它,但如果有人感觉特别好,我将如何扭转这个过程?即“101112131415”-->“abcdef”谢谢。
EDIT: This isn't homework, I'm entirely self taught. I have completed this project before in a different language and decided to try C++ to compare the differences and try to learn C++ in the process :)
编辑:这不是家庭作业,我完全是自学的。我之前用不同的语言完成了这个项目,并决定尝试 C++ 来比较差异并尝试在这个过程中学习 C++ :)
EDIT: I have roughly what I want, I just need a little bit of help converting this so that it applies to strings, thanks guys.
编辑:我大致有我想要的东西,我只需要一点帮助来转换它,以便它适用于字符串,谢谢大家。
#include <iostream>
#include <sstream>
#include <string>
int returnVal (char x)
{
return (int) x - 87;
}
int main()
{
char x = 'g';
std::cout << returnVal(x);
}
采纳答案by Ranveer
Each character has it's ASCII values. Try converting your characters into ASCII and then manipulate the difference.
每个字符都有它的 ASCII 值。尝试将您的字符转换为 ASCII,然后处理差异。
Example:
例子:
int x = 'a';
cout << x;
will print 97; and
将打印 97;和
int x = 'a';
cout << x - 87;
will print 10.
将打印 10。
Hence, you could write a function like this:
因此,您可以编写这样的函数:
int returnVal(char x)
{
return (int)x - 87;
}
to get the required output.
以获得所需的输出。
And your main program could look like:
您的主程序可能如下所示:
int main()
{
string s = "abcdef"
for (unsigned int i = 0; i < s.length(); i++)
{
cout << returnVal(s[i]);
}
return 0;
}
回答by Thomas Matthews
A portable method is to use a table lookup:
一种可移植的方法是使用表查找:
const unsigned int letter_to_value[] =
{10, 11, 12, /*...*/, 35};
// ...
letter = toupper(letter);
const unsigned int index = letter - 'A';
value = letter_to_value[index];
cout << index;
回答by Ranveer
How would I go about doing this?
我该怎么做呢?
By trying to do somethingfirst, and looking for help only if you feel you cannot advance.
首先尝试做某事,只有在您觉得自己无法进步时才寻求帮助。
That being said, the most obvious solution that comes to mind is based on the fact that characters (i.e. 'a'
, 'G'
) are really numbers. Suppose you have the following:
话虽如此,我想到的最明显的解决方案是基于字符(即'a'
, 'G'
)实际上是数字这一事实。假设您有以下内容:
char c = 'a';
You can get the number associated with c
by doing:
您可以c
通过执行以下操作获取关联的数字:
int n = static_cast<int>(c);
Then, add some offset to 'n':
然后,向 'n' 添加一些偏移量:
n += 10;
...and cast it back to a char
:
...并将其转换回 a char
:
c = static_cast<char>(n);
Note: The above assumes that characters are consecutive, i.e. the number corresponding to 'a'
is equal to the one corresponding to 'z'
minus the amount of letters between the two. This usually holds, though.
注意:以上假设字符是连续的,即对应的数字'a'
等于对应的数字'z'
减去两者之间的字母数。不过,这通常是成立的。
回答by roxdurazo
This can work
这可以工作
int Number = 123; // number to be converted to a string
int Number = 123; // number to be converted to a string
string Result; // string which will contain the result
string Result; // string which will contain the result
ostringstream convert; // stream used for the conversion
ostringstream convert; // stream used for the conversion
convert << Number; // insert the textual representation of 'Number' in the characters in the stream
convert << Number; // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str(); // set 'Result' to the contents of the stream
Result = convert.str(); // set 'Result' to the contents of the stream
you should add this headers
#include <sstream>
#include <string>
你应该添加这个标题
#include <sstream>
#include <string>
回答by parrowdice
What Daniel said, try it out for yourself.
Daniel 所说的,你自己试试。
As a starting point though, casting:
不过,作为一个起点,铸造:
int i = (int)string[0] + offset;
will get you your number from character, and: stringstream
will be useful too.
将从角色中获取您的号码,并且:stringstream
也很有用。
回答by Eric Postpischil
Many answers will tell you that characters are encoded in ASCII and that you can convert a letter to an index by subtracting 'a'
.
许多答案会告诉您字符是用 ASCII 编码的,您可以通过减去'a'
.
This is not proper C++. It is acceptable when your program requirements include a specification that ASCII is in use. However, the C++ standard alone does not require this. There are C++ implementations with other character sets.
这不是正确的 C++。当您的程序要求包括使用 ASCII 的规范时,这是可以接受的。但是,C++ 标准本身并不要求这样做。有其他字符集的 C++ 实现。
In the absence of knowledge that ASCII is in use, you can use translation tables:
在不知道 ASCII 正在使用的情况下,您可以使用转换表:
#include <limits.h>
// Define a table to translate from characters to desired codes:
static unsigned int Translate[UCHAR_MAX] =
{
['a'] = 10,
['b'] = 11,
…
};
Then you may translate characters to numbers by looking them up in the table:
然后,您可以通过在表中查找来将字符转换为数字:
unsigned char x = something;
int result = Translate[x];
Once you have the translation, you could print it as two digits using printf("%02d", result);
.
完成翻译后,您可以使用printf("%02d", result);
.
Translating in the other direction requires reading two characters, converting them to a number (interpreting them as decimal), and performing a similar translation. You might have a different translation table set up for this reverse translation.
在另一个方向翻译需要读取两个字符,将它们转换为数字(将它们解释为十进制),然后执行类似的翻译。您可能为此反向翻译设置了不同的翻译表。