2015-05-29 93 views
-4

我已經搜索了很多搜索解決方案,但並非如此! 我需要在char變量中搜索某個字符才能匹配。C++在char函數中搜索char?

char SOMECHAR[] = { 0XC1, 0XC2, 0XD4, 0XD3 }; 
    if (strchr(SOMECHAR, '0xD3') == NULL) { 
// i did not find it! 
    } 

strstr不起作用,strchar不起作用,螞蟻其他的解決辦法?

非常感謝!

+0

要在'char'變量來搜索一個'char'?這沒有意義,你的意思是'char *'?此外,你所擁有的代碼格式不正確,因爲'char'是一種類型。 – TartanLlama

+0

@Patratel請顯示功能定義。 –

+0

@TartanLlama哎呀,對不起,我的意思是:if(strchr(SOMECHAR,'0xD3')== NULL) – Patratel

回答

1

請注意,您需要小心使用值高與簽署char秒。
例如,0xD3 == (char)0xD3不正確,而0xD3 == (unsigned char)0xD3是。

std::find一個例子:

char SOMECHAR[] { 0x31, 0xC2, 0xD4, 0xD3 }; 
auto loc = std::find(std::begin(SOMECHAR), std::end(SOMECHAR), (char)0xD3); 
std::cout << "Found at " << std::distance(std::begin(SOMECHAR),loc) << std::endl; 
+0

謝謝你隊友:) – Patratel

+0

只需要注意:'strchr()'函數將其搜索的參數轉換爲'char',而memcmp()將它們處理的值視爲'unsigned char',而不管是否簽署了'char'。所以這些功能沒有你警告的問題。 –

0

下面是一個例子

#include <cstring> 

//... 

const char *s = "Patratel"; 

if (const char *p = std::strchr(s, 't')) 
{ 
    std::cout << "Character 't' is found at position " << p - s << std::endl; 
} 

如果字符數組不包含一個字符串,那麼你可以使用標準的功能memchr

例如

#include <cstring> 

//... 

char SOMECHAR[] = { '\xC1', '\xC2', '\xD4', '\xD3' }; 

if (char * p = (char *)std::memchr(SOMECHAR, '\xD3', sizeof(SOMECHAR))) 
{ 
    std::cout << "Character 't' is found at position " << p - SOMECHAR << std::endl; 
} 
+0

感謝弗拉德,但我不能使用const char *,因爲我的var只被定義爲char,並且我不能施放它,因爲它會崩潰... – Patratel

+0

@Patratel;如果變量的類型是char,那麼你可以簡單地比較一下,如果(c =='t'){/*...*/} –

+0

''0xD3''應該是'0xD3', –

1

兩件事情:

1)'0xD3'是不一樣的東西如0xD3'\xD3'這是您可能真正想要使用的值。

2)您需要在strchr()爲空時終止SOMECHAR,以便在未找到該字符的情況下定義好。或者,您可以使用memchr()並傳入SOMECHAR陣列的大小。

所以:

char SOMECHAR[] = { 0XC1, 0XC2, 0XD4, 0XD3, 0 }; 

if (strchr(SOMECHAR, 0xD3) == NULL) { 
    // i did not find it! 
} 

char SOMECHAR[] = { 0XC1, 0XC2, 0XD4, 0XD3 }; 

if (memchr(SOMECHAR, 0xD3, sizeof(SOMECHAR)) == NULL) { 
    // i did not find it! 
}