在Java中,字符串具有一个charAt()功能.
在C++中,该功能很简单 stringname[INDEX]
但是,如果我想在整数的某个索引处使用特定数字,该怎么办?
例如
int value = 9123;
Run Code Online (Sandbox Code Playgroud)
假设我想使用索引0,这只是9.
有没有办法在整数中使用索引?
And*_*nck 15
int value = 9123;
std::stringstream tmp;
tmp << value;
char digit = (tmp.str())[0];
Run Code Online (Sandbox Code Playgroud)
不,没有标准函数从整数中提取十进制数字.
在C++ 11中,有一个转换为字符串的函数:
std::string string = std::to_string(value);
Run Code Online (Sandbox Code Playgroud)
如果你不能使用C++ 11,那么你可以使用字符串流:
std::ostringstream stream;
stream << value;
std::string string = stream.str();
Run Code Online (Sandbox Code Playgroud)
或旧式C格式:
char buffer[32]; // Make sure it's large enough
snprintf(buffer, sizeof buffer, "%d", value);
std::string string = buffer;
Run Code Online (Sandbox Code Playgroud)
或者如果你只想要一个数字,你可以算术地提取它:
int digits = 0;
for (int temp = value; temp != 0; temp /= 10) {
++digits;
}
// This could be replaced by "value /= std::pow(10, digits-index-1)"
// if you don't mind using floating-point arithmetic.
for (int i = digits-index-1; i > 0; --i) {
value /= 10;
}
int digit = value % 10;
Run Code Online (Sandbox Code Playgroud)
以合理的方式处理负数仍然是读者的练习.
您可以使用以下公式(伪代码):
currDigit = (absolute(value) / 10^index) modulo 10; // (where ^ is power-of)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4198 次 |
| 最近记录: |