在C++中如何在字符串中查找int

In C++ how to find an int in a string

本文关键字:查找 int 字符串 C++      更新时间:2023-10-16

如果可能的话,我想这样做, char buff[]="MA A8C : B12A : D14C: ... etc." int myId=12; if (myId exist in Buff){print i found it}else{it doesn't not exist}

所以简单地说,我想表明这个整数确实存在于这个字符串中,我不需要位置,也不需要它被提到的位置或次数,或者任何复杂的事情,我所有的搜索都会导致有人试图找到这个int的位置。。。但在我的情况下,我只想找到它是不是有回报1不在那里?返回0。感谢

你不能直接这么做。您可以先将数字转换为字符串,然后在buff中搜索该字符串。

你可以使用C方法:

char temp[10];
sprintf(temp, "%d", myId);
if ( strstr(buff, temp) != NULL )
{
   // Found it.
}
else
{
   // Did not find it.
}

如果你想使用更多的C++方法,你可以使用:

auto found = std::string(buff).find(std::to_string(myID));
if ( found != std::string::npos )
{
   // Found it.
}
else
{
   // Did not find it.
}