Имя: Пароль:
IT
Админ
[Qt] QString::compare(...) - как оно работает?
0 bvn13
 
29.01.10
15:59
есть хороший метод сравнения строк. но вот описание для него явно чего-то недоговаривает... подскажите, кто работал и знает.

int QString::compare ( const QString & s1, const QString & s2, Qt::CaseSensitivity cs )   [static]
Compares s1 with s2 and returns an integer less than, equal to, or greater than zero if s1 is less than, equal to, or greater than s2.

If cs is Qt::CaseSensitive, the comparison is case sensitive; otherwise the comparison is case insensitive.

Case sensitive comparison is based exclusively on the numeric Unicode values of the characters and is very fast, but is not what a human would expect. Consider sorting user-visible strings with localeAwareCompare().

    int x = QString::compare("aUtO", "AuTo", Qt::CaseInsensitive);  // x == 0
    int y = QString::compare("auto", "Car", Qt::CaseSensitive);     // y > 0
    int z = QString::compare("auto", "Car", Qt::CaseInsensitive);   // z < 0


почему их пример именно так работает?
в чем логика?
почему y>0 и z<0 ???
1 Ёпрст
 
гуру
29.01.10
16:00
int QString::compare ( const QString & s1, const QString & s2 )   [static]

Лексически сравнивает строки s1 и s2 и возвращает целое число меньшее, равное или большее чем ноль если s1 меньше, равно или больше чем s2.

Сравнение осуществляется исключительно не числовых значениях символов Unicode и выполняется очень быстро, но работает не так, как человек мог-бы ожидать. Сортировка очевидная для пользователя осуществляется с помощью localeAwareCompare().

   int x = QString::compare("auto", "auto");   // x == 0
   int y = QString::compare("auto", "car");    // y < 0
   int z = QString::compare("car", "auto");    // z > 0
2 bvn13
 
29.01.10
16:02
(1) не ну не блин!? "работает не так, как человек мог-бы ожидать. "... а нафига это вообще нужно?

а что есть по аналогии со strcmp()?
3 bvn13
 
29.01.10
16:07
+(2) я так понимаю, что вот этот:

int QString::localeAwareCompare ( const QStringRef & other ) const
4 orefkov
 
29.01.10
16:07
Все правильно работает.
С учетом регистра символ 'a' идет ПОСЛЕ 'C' (можешь посмотреть в любой таблице кодировок), след-но "auto" > "Car".
Без учета регистра "auto" < "Car"
5 orefkov
 
29.01.10
16:08
(3)
strcmp("auto", "Car") > 0
6 Ёпрст
 
гуру
29.01.10
16:09
int QString::localeAwareCompare ( const QString & s1, const QString & s2 )   [static]

Сравнивает s1 с s2 и возвращает целое значение меньшее, равное или большее ноля если s1 меньше, равно или больше s2.

Сравнение выполняется способом зависящим от используемой локализации и платформы. Используйте данную функцию для представлению сортированных списков строк пользователю.

См. также compare() и QTextCodec::locale().
7 trdm
 
29.01.10
16:25
Просьба к модераторам: добавьте пожалуйста метку Qt
8 trdm
 
29.01.10
16:31
Сенк. воткнул метку Qt в тему.
9 trdm
 
29.01.10
16:36
10 bvn13
 
29.01.10
16:41
блин, а есть что-нибудь наподобие привычного СтрНайти?
11 trdm
 
29.01.10
16:43
int QString::indexOf ( const QString & str, int from = 0, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
12 trdm
 
29.01.10
16:44
Returns the index position of the first occurrence of the string str in this string, searching forward from index position from. Returns -1 if str is not found.
13 trdm
 
29.01.10
16:45
+
bool contains ( const QString & str, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
bool contains ( QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
bool contains ( const QRegExp & rx ) const
bool contains ( QRegExp & rx ) const
14 trdm
 
29.01.10
16:48
+
bool endsWith ( const QString & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
bool endsWith ( const QLatin1String & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
bool endsWith ( const QChar & c, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
# int lastIndexOf ( const QString & str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
int lastIndexOf ( const QLatin1String & str, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
int lastIndexOf ( QChar ch, int from = -1, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
int lastIndexOf ( const QRegExp & rx, int from = -1 ) const
int lastIndexOf ( QRegExp & rx, int from = -1 ) const
# bool startsWith ( const QString & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
bool startsWith ( const QLatin1String & s, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
bool startsWith ( const QChar & c, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const
(10) Совсем плохо с поиском в Ассистанте?
Есть два вида языков, одни постоянно ругают, а вторыми никто не пользуется.