Created
July 29, 2012 12:02
-
-
Save linquize/3198205 to your computer and use it in GitHub Desktop.
C# StrCmpLogical
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static bool IsDigit(char c) | |
{ | |
return c >= '0' && c <= '9'; | |
} | |
unsafe static int UnsafeStrCmpLogical(string s1, string s2) | |
{ | |
fixed (char* p1 = s1) | |
{ | |
fixed (char* p2 = s2) | |
{ | |
char* x = p1; | |
char* y = p2; | |
while (*x != '\0' && *y != '\0') | |
{ | |
char a = *x; | |
char b = *y; | |
if (!(IsDigit(a) && IsDigit(b))) | |
{ | |
if (a > b) | |
return 1; | |
if (a < b) | |
return -1; | |
x++; | |
y++; | |
} | |
else | |
{ | |
bool zero = true; | |
char* m = x; | |
while (IsDigit(*m)) | |
{ | |
if (*m == '0' && zero) | |
x++; | |
else | |
zero = false; | |
m++; | |
} | |
zero = true; | |
char* n = y; | |
while (IsDigit(*n)) | |
{ | |
if (*n == '0' && zero) | |
y++; | |
else | |
zero = false; | |
n++; | |
} | |
if (m - x > n - y) | |
return 1; | |
else if (m - x < n - y) | |
return -1; | |
while (x < m) | |
{ | |
if (*x > *y) | |
return 1; | |
if (*x < *y) | |
return -1; | |
x++; | |
y++; | |
} | |
} | |
} | |
if (*x > *y) | |
return 1; | |
if (*x < *y) | |
return -1; | |
return 0; | |
} | |
} | |
} | |
static int SafeStrCmpLogical(string s1, string s2) | |
{ | |
int x = 0; | |
int y = 0; | |
while (s1[x] != '\0' && s2[y] != '\0') | |
{ | |
char a = s1[x]; | |
char b = s2[y]; | |
if (!(IsDigit(a) && IsDigit(b))) | |
{ | |
if (a > b) | |
return 1; | |
if (a < b) | |
return -1; | |
x++; | |
y++; | |
} | |
else | |
{ | |
bool zero = true; | |
int m = x; | |
while (IsDigit(s1[m])) | |
{ | |
if (s1[m] == '0' && zero) | |
x++; | |
else | |
zero = false; | |
m++; | |
} | |
zero = true; | |
int n = y; | |
while (IsDigit(s2[n])) | |
{ | |
if (s2[n] == '0' && zero) | |
y++; | |
else | |
zero = false; | |
n++; | |
} | |
if (m - x > n - y) | |
return 1; | |
else if (m - x < n - y) | |
return -1; | |
while (x < m) | |
{ | |
if (s1[x] > s2[y]) | |
return 1; | |
if (s1[x] < s2[y]) | |
return -1; | |
x++; | |
y++; | |
} | |
} | |
} | |
if (s1[x] > s2[y]) | |
return 1; | |
if (s1[x] < s2[y]) | |
return -1; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that it is totally different from win32 API StrCmpLogicalW