2014-12-26 78 views

回答

-1

如果你的意思是标准类std::string那么它有方法找到

例如

#include <iostream> 
#include <string> 

//... 

std::string s("123456789"); 

auto n = s.find('5'); 

if (n != std::string::npos) 
{ 
    std::cout << "character '5' found at position " << n << std::endl; 
} 

您可以编写使用此方法的功能。例如

bool find_char(const std::string &s, char c) 
{ 
    return (s.find(c) != std::string::npos); 
} 

如果您希望函数返回1或0,那么只需将其返回类型更改为int即可。

int find_char(const std::string &s, char c) 
{ 
    return (s.find(c) != std::string::npos); 
} 

如果你的意思的字符数组那么可以使用任一标准算法std::findstd::any_of或标准C函数strchr

例如

#include <iostream> 
#include <cstring> 

//... 

char s[] = "123456789"; 

char *p = std::strchr(s, '5'); 


if (p != nullptr) 
{ 
    std::cout << "character '5' found at position " << p - s << std::endl; 
} 

或者,如果使用算法std::find则代码将看起来像

#include <iostream> 
#include <algorithm> 
#include <iterator> 

//... 

char s[] = "123456789"; 

char *p = std::find(std::begin(s), std::end(s), '5'); 

if (p != std::end(s)) 
{ 
    std::cout << "character '5' found at position " << std::distance(s, p) << std::endl; 
} 
+0

我已经看到发现。问题是我希望它返回1如果字符存在或0,如果它不。 – rebel1234

+1

@ rebel1234这不是问题 – keyser

+0

@ rebel1234在这种情况下,您可以简单地将该方法的调用包装在一个函数中,该函数将返回true或false。 –

0

下列功能就会停止,只要找到一个寻找的字符:

std::string str ("My string with: a"); 

if (str.find_first_of("a")!=std::string::npos) 
{ 
    return 1; 
} 
else 
{ 
    return 0; 
} 
相关问题