比较字符串与整数的位置

Compare position of a string with an integer

例如:

字符串:1 2 3 4 5

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

if(atoi(string[i]) == 值)

但这好像不行,我需要改成相反的方式吗? (将 int 转换为字符串,然后是 strcmp?) 提前致谢

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

atoiconst char* 作为参数,但您将其传递给一个字符。你需要做的是这样的:

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

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

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

这是可行的,因为数字以 48 的 ascii 值开始,而您一次只检查一个字符。

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