On-line: гостей 0. Всего: 0 [подробнее..]
Программисты всех стран, объединяйтесь!

АвторСообщение



ссылка на сообщение  Отправлено: 20.11.15 10:03. Заголовок: Compare two string numeric value


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

Спасибо: 0 
ПрофильЦитата Ответить
Новых ответов нет [см. все]





ссылка на сообщение  Отправлено: 20.11.15 10:53. Заголовок: You can compare them..


You can compare them in the lexicographical order.

To define the corresponding logical operator introduce a wrapper around the strings.
For example
 
#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;
}

The program output is
 
a < b is true
"001" < "2" is true


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

 
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;
}
}


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
 
//...
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 );
}



Спасибо: 1 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 20.11.15 12:26. Заголовок: Wow thanks that all ..


Wow thanks that all i want

Спасибо: 0 
ПрофильЦитата Ответить
Ответ:
1 2 3 4 5 6 7 8 9
большой шрифт малый шрифт надстрочный подстрочный заголовок большой заголовок видео с youtube.com картинка из интернета картинка с компьютера ссылка файл с компьютера русская клавиатура транслитератор  цитата  кавычки моноширинный шрифт моноширинный шрифт горизонтальная линия отступ точка LI бегущая строка оффтопик свернутый текст

показывать это сообщение только модераторам
не делать ссылки активными
Имя, пароль:      зарегистрироваться    
Тему читают:
- участник сейчас на форуме
- участник вне форума
Все даты в формате GMT  3 час. Хитов сегодня: 10
Права: смайлы да, картинки да, шрифты да, голосования нет
аватары да, автозамена ссылок вкл, премодерация откл, правка нет