Click to See Complete Forum and Search --> : Advanced string comparison


Mapisto
October 2nd, 2005, 01:18 PM
Hi guys,

I need to find a way to compare two strings which include numbers within.
The standard "strcmp" don't exclude numbers, so "a101" < "a12".

Are you familiar with an implementation which sloves it?

Regards,
Mapisto.

Ajay Vijay
October 2nd, 2005, 01:43 PM
Do you want to compare numbers after ONE character? If this is the case, you can just have a pointer that points to second character's address and perform atoi/l:char sourcestr1[] = "a101", sourcestr2[] = "a12";
int a,b;
char *p;
p=sourcestr1 + 1;
a=atol(p);
b=atol(sourcestr2 + 1);
if(a>b)...

Mapisto
October 2nd, 2005, 02:57 PM
Of course not, I meant to more general solution. So, i've overcomed my laziness and eventually coded it:


#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>



int strnumcmp( const char* str1, const char* str2 )
{
unsigned int str1len = strlen(str1);
unsigned int str2len = strlen(str2);
unsigned long res1 = 0, res2 =0;
char *stopstring1, *stopstring2;
for(unsigned int i =0; i < str1len; i++) {
if (i > str2len)
return 1;

if (isdigit(str1[i]) && isdigit(str2[i]))
{
res1 = strtoul(&str1[i], &stopstring1, 10);
str1 = stopstring1;
str1len = strlen(stopstring1);
res2 = strtoul(&str2[i], &stopstring2, 10);
str2 = stopstring2;
str1len = strlen(stopstring1);
if (res1 > res2)
return 1;
else if ( res1 < res2)
return -1;
i = 0;
continue;
}

if (str1[i] > str2[i]) {
return 1;
}
else if(str1[i] < str2[i] ) {
return -1;
}

}
return 0;
}

int main( char **argv, int argc ) {
const char* str1 = "e110xy";
const char* str2 = "e110xy";

printf( "%d\n", strnumcmp(str1,str2) );

return 0;
}



enjoy.

Ajay Vijay
October 2nd, 2005, 11:31 PM
int main( char **argv, int argc ) { Which compiler you are using? :D

Ejaz
October 2nd, 2005, 11:32 PM
[ Moved Thread ]