c语言中 compare函数,C/C++中的字符串比较函数strcmp/memcmp/CString.Compare/CStrin
memcmp和strncmp的區別
一、memcmp含義
Compare characters in two buffers.
int memcmp(? ? const void* buf1,? ? const void* buf2,? ? size_t count );inline int wmemcmp (? ?const? wchar_t* buf1, const wchar_t* buf2, size_t count);
Parameters
buf1
:
First buffer.
buf2
:
Second buffer.
count
:
Number of characters.
Return Values? ?:
The return value indicates the relationship between the buffers.
Return ValueRelationship of First count Bytes of buf1 and buf2? ? ? ? ?< 0? ? ? ? ?buf1 less than buf2? ? ? ? ?0? ? ? ? ?buf1 identical to buf2? > 0? ? ?buf1 greater than buf2
二、memcmp與strcmp的區別
int? ?memcmp(const? ?void? ?*? ?cs,const? ?void? ?*? ?ct,size_t? ?count)
{
const? ?unsigned? ?char? ?*su1,? ?*su2;
int? ?res? ?=? ?0;
for(? ?su1? ?=? ?cs,? ?su2? ?=? ?ct;? ?0? ?
if? ?((res? ?=? ?*su1? ?-? ?*su2)? ?!=? ?0)
break;
return? ?res;
}
int? ?strncmp(const? ?char? ?*? ?cs,const? ?char? ?*? ?ct,size_t? ?count)
{
register? ?signed? ?char? ?__res? ?=? ?0;
while? ?(count)? ?{
if? ?((__res? ?=? ?*cs? ?-? ?*ct++)? ?!=? ?0? ?||? ?!*cs++)
break;
count--;
}
return? ?__res;
}
1、這兩個函數的差別其實還是挺大的,差別在這里:? ? ? ? 對于memcmp(),如果兩個字符串相同而且count大于字符串長度的話,memcmp不會在\0處停下來,會繼續比較\0后面的內存單元,直到_res不為零或者達到count次數。? ? ? ? ?對于strncmp(),由于((__res? ?=? ?*cs? ?-? ?*ct++)? ?!=? ?0? ?||? ?!*cs++)的存在,比較必定會在最短的字符串的末尾停下來,即使count還未為零。具體的例子:? ? ? ? ?char? ?a1[]="ABCD";? ? ? char? ?a2[]="ABCD";? ? ? ? ? 對于memcmp(a1,a2,10),memcmp在兩個字符串的\0之后繼續比較? ? ? 對于strncmp(a1,a2,10),strncmp在兩個字符串的末尾停下,不再繼續比較。? ? ? ? ? 所以,如果想使用memcmp比較字符串,要保證count不能超過最短字符串的長度,否則結果有可能是錯誤的。
2、strncmp("abcd",? ?"abcdef",? ?6)? ?=? ?0。比較次數是一樣的:? ? ? ?memcmp:在比較到第5個字符也就是'\0',*su1? ?-? ?*su2的結果顯然不等于0,所以滿足條件跳出循環,不會再進行后面的比較。我想在其他情況下也一樣。? ? ? ?strncmp:同樣的道理再比較到第5個字符時結束循環,其實strncmp中“!*cs++”完全等同于“!*ct++”,其作用僅在于當兩個字符串相同的情形下,防止多余的比較次數。
來源:
CString::CompareNoCase與CString::Compare的區別
函數原型:int CompareNoCase( LPCTSTR lpsz ) const;? 返回值: 該函數對兩個CString對象進行,如果內容完全一致則返回0;如果小于lpsz,則返回為-1;如果大于lpsz,則返回1。比如,利用CompareNoCase比較str與lpsz,等同于區分大小寫比較str與lpsz的第一個相異字符,如果str該處的字符比lpsz大,則字符串str大于lpsz,返回1;如果str該處的字符比lpsz小,則字符串str小于lpsz,返回-1;str與lpsz內容完全一致則返回0
說明: 此成員函數通過使用通用文本函數_tcsicmp來比較這個CString對象和另一個字符串。此通用文本函數_tcsicmp是在TCHAR.H中定義 的,根據在編譯時設置的字符來與_stricmp,_wcsicmp,或_mbsicmp對應。這些函數的每一個都根據當前使用的代碼頁來進行一次區分大 小寫的比較,而且不會被現場影響。
與Compare的區別
CompareNoCase為不區分大小寫比較,而Compare為區分大小寫比較
來源:
總結
以上是生活随笔為你收集整理的c语言中 compare函数,C/C++中的字符串比较函数strcmp/memcmp/CString.Compare/CStrin的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringMVC 数据绑定全面示例(复
- 下一篇: ssi整合,即spring、spring