如何使用c ++将字符串搜索到字符串数组?

时间:2016-03-07 14:20:55

标签: c++ arrays string algorithm

我需要将字符串搜索到字符串数组中。特别是,我有一个带有名称的字符串变量,我需要将此名称搜索为字符串数组,但我无法解决我的问题。

这是我的代码:

connessionesocket(sock,server);

    int result=0,f=0;
    bool trovato=false;
    do{ 

        if(result=(recv(sock, estratto, sizeof(estratto),0))>0)
        {
            string appo(estratto);
            cout << "Appo: "<< appo<< endl; 
            if ( std::find( std::begin( numeri ), std::end( numeri ), appo ) != std::end( numeri ) )
            {
                    cout << "Correct" << endl;  
            }   
            f++;                             
        }               

        if(result==0)
        {
            cout<< "Fine";
        }
    }
    while(result>0);
    close(sock);

有什么问题?为什么我没有看到cout << "Correct" <<endl;

这是我的结果:

I need, so the result is the same of the matrix to see the "Correct" message

1 个答案:

答案 0 :(得分:5)

您可以使用标准算法std::find。例如

#include <algorithm>

//...

if ( std::find( names, names + 15, appo ) != names + 15 )
{
        cout << "Correct" << endl;  
}   

或者如果范围对应于整个数组,那么

#include <algorithm>
#include <iterator>

//...

if ( std::find( std::begin( names ), std::end( names ), appo ) != std::end( names ) )
{
        cout << "Correct" << endl;  
}