mirror of
https://github.com/hairrrrr/C-CrashCourse.git
synced 2026-06-28 01:26:15 +08:00
2-8
This commit is contained in:
29
C Crash Course/13 String/Prelesson/code/mystrcmp/VSstrcmp.c
Normal file
29
C Crash Course/13 String/Prelesson/code/mystrcmp/VSstrcmp.c
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
//这是我能理解的格式
|
||||||
|
int mystrcmp(char* str1, char* str2) {
|
||||||
|
|
||||||
|
int ret = 0;
|
||||||
|
|
||||||
|
while ((ret = ((unsigned char)*str1 - (unsigned char)*str2)) == 0 && *str1) {
|
||||||
|
++str1, ++str2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//原版在这里
|
||||||
|
int __cdecl strcmp(
|
||||||
|
const char* src,
|
||||||
|
const char* dst
|
||||||
|
)
|
||||||
|
{
|
||||||
|
int ret = 0;
|
||||||
|
|
||||||
|
while ((ret = *(unsigned char*)src - *(unsigned char*)dst) == 0 && *dst)
|
||||||
|
{
|
||||||
|
++src, ++dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
//这里不太理解,那个大神理解了可以给我讲一下,谢谢
|
||||||
|
return ((-ret) < 0) - (ret < 0); // (if positive) - (if negative) generates branchless code
|
||||||
|
}
|
||||||
11
C Crash Course/13 String/Prelesson/code/mystrcmp/main.c
Normal file
11
C Crash Course/13 String/Prelesson/code/mystrcmp/main.c
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
|
||||||
|
char* str1 = "Hello ";
|
||||||
|
char* str2 = "Hello";
|
||||||
|
|
||||||
|
printf("%d\n", mystrcmp(str1, str2));
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
int mystrcmp(char* str1, char* str2) {
|
||||||
|
|
||||||
|
while (*str1 == *str2 && *str1)
|
||||||
|
++str1, ++str2;
|
||||||
|
|
||||||
|
return (*str1 - *str2);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user