Форум » C/C++ для начинающих (C/C++ for beginners) » Compare two string numeric value » Ответить

Compare two string numeric value

ramees: I have two string variable that handle big values like string a = "24637384636374849"; string b = "67484624274849494"; I need to compare this string like a < b , b < a is there an essay way to do this or i need to write separate function for this . I googled it but i couldn't find any useful info

Ответов - 2

Сыроежка: You can compare them in the lexicographical order. To define the corresponding logical operator introduce a wrapper around the strings. For example [pre2] #include <iostream> #include <iomanip> #include <string> struct BigNumber { BigNumber( const std::string &value ) : value( value ) {} std::string value; }; bool operator <( const BigNumber &a, const BigNumber &b ) { std::string::size_type pos1 = a.value .find_first_not_of( '0' ); std::string::size_type pos2 = b.value.find_first_not_of( '0' ); return a.value.compare( pos1, a.value.size() - pos1, b.value, pos2, b.value.size() - pos2 ) < 0; } int main() { std::string a = "24637384636374849"; std::string b = "67484624274849494"; std::cout << "a < b is " << std::boolalpha << ( BigNumber( a ) < BigNumber( b ) ) << std::endl; std::cout << "\"001\" < \"2\" is " << std::boolalpha << ( BigNumber( "001" ) < BigNumber( "2" ) ) << std::endl; }[/pre2] The program output is [pre2] a < b is true "001" < "2" is true[/pre2] Of course you need to provide that the strings contain only digits. Only you should also append the operator with the code that will process situations when one of the strings or both are empty or contain only zeroe(s). That is what is the result of comparing a string that contains only zeroe(s) and an empty string? For example something like the following [pre2] bool operator <( const BigNumber &a, const BigNumber &b ) { std::string::size_type pos1 = a.value .find_first_not_of( '0' ); std::string::size_type pos2 = b.value.find_first_not_of( '0' ); if ( pos1 == std::string::npos && pos2 == std::string::npos ) { return false; } else if ( pos1 == std::string::npos ) { return true; } else if ( pos2 == std::string::npos ) { return false; } else { return a.value.compare( pos1, a.value.size() - pos1, b.value, pos2, b.value.size() - pos2 ) < 0; } }[/pre2] Take into account that the code I showed does not considers the situation when one string is longer than other. Of course before applying member function compare you have to compare the resulting lengths of the compared substring. If one string is larger than other then the corresponding number is greater than the number in other string. For example [pre2] //... else { return ( a.value.size() - pos1 < b.value.size() - pos2 ) || ( !( b.value.size() - pos2 < a.value.size() - pos1 ) && a.value.compare( pos1, a.value.size() - pos1, b.value, pos2, b.value.size() - pos2 ) < 0 ); } [/pre2]

ramees: Wow thanks that all i want



полная версия страницы