2014-12-26 77 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; 
} 
相關問題