|
int strcmp (const char* s1, const char* s2)
int strncmp (const char* s1, const char* s2, int n) int strcasecmp (const char* s1, const char* s2) int strncasecmp (const char* s1, const char* s2, int n) |
strcmp e strcasecmp accettano le due stringhe da confrontare, sotto forma di puntatori a caratteri costanti. Esse tornano zero se le due stringhe sono identiche, un valore negativo se la prima stringa è minore della seconda, un valore positivo altrimenti. La differenza tra le due è che strcasecmp non tiene conto della differenza tra maiuscole e minuscole, mentre strcmp sì ; si veda il seguente:
// ex6_6_3
#include <iostream.h>
#include <string.h>
void main() {
char* s1 = "TEX";
char* s2 = "tex";
if ( strcmp(s1, s2) < 0 )
cout << s1 << " < " << s2 << "\n";
if ( strcasecmp(s1, s2) == 0)
cout << s1 << " = " << s2 << "\n";
char* t1 = "Excite";
char* t2 = "Altavista";
if ( strcmp(t1, t2) > 0)
cout << t1 << " > " << t2 << "\n";
}
output:
TEX < tex
TEX = tex
Excite > Altavista
Si noti che, nel caso di strcmp, i caratteri maiuscoli sono considerati minori di quelli minuscoli.
Le funzioni strncmp e strncasecmp si comportano esattamente come, rispettivamente, strcmp e strcasecmp ma confrontano solo i primi n caratteri delle due stringhe.
Vediamo ora un esempio che, grazie a queste funzioni di confronto, ci permette di ordinare un elenco di nomi:
// ex6_6_4
// ordina un array di stringhe
// con il metodo `selection sort'
#include <iostream.h>
#include <string.h>
const int MAX_LUNG = 20;
const int MAX_STR = 50;
void scambia (char s1[MAX_STR], char s2[MAX_STR]) {
// stringa ausiliaria
char aux[MAX_STR];
strcpy (aux, s1);
strcpy (s1, s2);
strcpy (s2, aux);
}
void ordina (char elenco[MAX_LUNG][MAX_STR], int n) {
for (int i = 0; i < n; i++) {
int min = i;
for (int j = i + 1; j < n; j++)
if ( strcmp(elenco[j], elenco[min]) < 0 )
scambia (elenco[j], elenco[min]);
}
}
// ritorna il numero di stringhe immesse dall'utente
int ingresso (char elenco[MAX_LUNG][MAX_STR]) {
cout << "scrivi `0' per terminare\n";
// stringa ausiliaria
char buffer[MAX_LUNG];
int i = 0;
for ( ; ; ) {
cin >> buffer;
if ( strcmp(buffer, "0") == 0)
break;
strcpy (elenco[i], buffer);
i++;
}
return i;
}
void stampa (const char elenco[MAX_LUNG][MAX_STR], int n) {
for (int i = 0; i < n; i++)
cout << elenco[i] << "\n";
}
void main() {
char elenco[MAX_LUNG][MAX_STR];
int n = ingresso (elenco);
ordina (elenco, n);
stampa (elenco, n);
}
esempio di output:
scrivi `0' per terminare
Lagrange
Laplace
Weiestrass
Cauchy
Torricelli
Abel
Zorn
Volterra
Gauss
0
Abel
Cauchy
Gauss
Lagrange
Laplace
Torricelli
Volterra
Weiestrass
Zorn
Naturalmente abbiamo dovuto adattare, oltre alla funzione selectionsort, anche la scambia dell'esempio ex6_3_1.cpp. Una osservazione: una stringa si rappresenta come un array, per cui noi abbiamo costruito un array di array, cioè una tabella (o matrice), di cui parleremo nel prossimo paragrafo.