比较字符串与整数的位置

标签 c string int

每个示例:

字符串:1 2 3 4 5

我想创建一个 for 循环来将每个字符串位置与用户提供的 int 进行比较。我试过了

if(atoi(字符串[i]) == 值)

但这似乎不起作用,我需要将其改为相反的方式吗? (将 int 转为 string,然后转为 strcmp?) 提前致谢

最佳答案

我假设您是在 C++ 中执行此操作。

atoi 采用 const char* 作为参数,但您向其传递一个字符。您需要做的是这样的:

std::string str(1, string[i]);
if(atoi(str.c_str()) == value)
...

或者你可以完全跳过 atoi 并直接执行

if(string[i]-48 == value)
...

这是可行的,因为数字从 ascii 值 48 开始,并且您一次仅检查一个字符。

免责声明:我还假设 string 是 char[],因此 string[i]char

关于比较字符串与整数的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29636583/

相关文章:

通过 SMBus/I2C 更改带有 bcm2835 的 mlx90614 从机地址

java - Eclipse Java(非 Android)中的 Strings.xml 或 String 资源

c - c中声明但未初始化的int变量的值

java - 将 byte 转换为 int,反之亦然

Java错误: "incompatible types: int cannot be converted to Player

c++ - 是否可以在控制台中用 C 打印孟加拉语?

java - 程序执行时间

C语言 : what does this error mean?

ruby - 为什么某些 Ruby 方法(如 String#replace)会改变变量的副本?

java - 使用或不使用正则表达式解析字符串