classe std::string in C++
Il C++ ha nella sua definizione un modo per rappresentare a sequenza di caratteri come oggetto della classe . Questa classe si chiama std:: string. La classe string memorizza i caratteri come una sequenza di byte con la funzionalità di consentire accesso al carattere a byte singolo .
Stringa e array di caratteri
| Corda | Matrice di caratteri |
|---|---|
| Una stringa è a classe che definisce gli oggetti essere rappresentato come un flusso di caratteri. | Un array di caratteri è semplicemente un file matrice di caratteri che può essere terminato con un carattere nullo. |
| Nel caso delle stringhe, la memoria lo è allocati dinamicamente . È possibile allocare più memoria in fase di esecuzione su richiesta. Poiché nessuna memoria è preallocata, nessuna memoria è sprecata . | La dimensione dell'array di caratteri deve essere allocato staticamente , se necessario, non è possibile allocare più memoria in fase di esecuzione. Assegnato inutilizzato anche la memoria è sprecata |
| Poiché le stringhe sono rappresentate come oggetti, nessun decadimento dell'array si verifica. | C'è un minaccia di decadimento dell'array nel caso dell'array di caratteri. |
| Le stringhe sono più lente rispetto all'implementazione rispetto all'array di caratteri. | Implementazione di l'array di caratteri è più veloce di std:: stringa. |
| La classe String definisce una serie di funzionalità che consentono molteplici operazioni sulle stringhe. | Matrici di caratteri non offrire molti funzioni integrate per manipolare le corde. |
Operazioni sulle stringhe
1) Funzioni di ingresso
| Funzione | Definizione |
|---|---|
| getline() | Questa funzione viene utilizzata per memorizzare un flusso di caratteri immessi dall'utente nella memoria dell'oggetto. |
| respingere() | Questa funzione viene utilizzata per inserire un carattere alla fine della stringa. |
| pop_back() | Introdotta da C++11 (per le stringhe), questa funzione viene utilizzata per eliminare l'ultimo carattere dalla stringa. |
Esempio:
CPP
// C++ Program to demonstrate the working of> // getline(), push_back() and pop_back()> #include> #include // for string class> using> namespace> std;> > // Driver Code> int> main()> {> > // Declaring string> > string str;> > > // Taking string input using getline()> > getline(cin, str);> > > // Displaying string> > cout < <> 'The initial string is : '> ;> > cout < < str < < endl;> > > // Inserting a character> > str.push_back(> 's'> );> > > // Displaying string> > cout < <> 'The string after push_back operation is : '> ;> > cout < < str < < endl;> > > // Deleting a character> > str.pop_back();> > > // Displaying string> > cout < <> 'The string after pop_back operation is : '> ;> > cout < < str < < endl;> > > return> 0;> }> |
Produzione
The initial string is : The string after push_back operation is : s The string after pop_back operation is :
Complessità temporale: O(1)
Complessità spaziale: O(n) dove n è la dimensione della stringa
2) Funzioni di capacità
| Funzione | Definizione |
|---|---|
| capacità() | Questa funzione restituisce la capacità allocata alla stringa, che può essere uguale o superiore alla dimensione della stringa. Viene allocato spazio aggiuntivo in modo che quando i nuovi caratteri vengono aggiunti alla stringa, le operazioni possano essere eseguite in modo efficiente. |
| ridimensionare() | Questa funzione modifica la dimensione della stringa, la dimensione può essere aumentata o diminuita. |
| lunghezza() | Questa funzione trova la lunghezza della stringa. |
| rimpicciolirsi per starci dentro() | Questa funzione diminuisce la capacità della stringa e la rende pari alla capacità minima della stringa. Questa operazione è utile per risparmiare ulteriore memoria se siamo sicuri di non dover fare ulteriori aggiunte di caratteri. |
Esempio:
CPP
// C++ Program to demonstrate the working of> // capacity(), resize() and shrink_to_fit()> #include> #include // for string class> using> namespace> std;> > // Driver Code> int> main()> {> > // Initializing string> > string str => 'geeksforgeeks is for geeks'> ;> > > // Displaying string> > cout < <> 'The initial string is : '> ;> > cout < < str < < endl;> > > // Resizing string using resize()> > str.resize(13);> > > // Displaying string> > cout < <> 'The string after resize operation is : '> ;> > cout < < str < < endl;> > > // Displaying capacity of string> > cout < <> 'The capacity of string is : '> ;> > cout < < str.capacity() < < endl;> > > // Displaying length of the string> > cout < <> 'The length of the string is :'> < < str.length()> > < < endl;> > > // Decreasing the capacity of string> > // using shrink_to_fit()> > str.shrink_to_fit();> > > // Displaying string> > cout < <> 'The new capacity after shrinking is : '> ;> > cout < < str.capacity() < < endl;> > > return> 0;> }> |
Produzione
The initial string is : geeksforgeeks is for geeks The string after resize operation is : geeksforgeeks The capacity of string is : 26 The length of the string is :13 The new capacity after shrinking is : 13
Complessità temporale: O(1)
Complessità spaziale: O(n) dove n è la dimensione della stringa
3) Funzioni dell'iteratore
| Funzione | Definizione |
|---|---|
| inizio() | Questa funzione restituisce un iteratore all'inizio della stringa. |
| FINE() | Questa funzione restituisce un iteratore successivo alla fine della stringa. |
| rbegin() | Questa funzione restituisce un iteratore inverso che punta alla fine della stringa. |
| rendere() | Questa funzione restituisce un iteratore inverso che punta al precedente dell'inizio della stringa. |
| cbegin() | Questa funzione restituisce un iteratore costante che punta all'inizio della stringa, non può essere utilizzata per modificare il contenuto a cui punta. |
| alcuni() | Questa funzione restituisce un iteratore costante che punta alla fine successiva della stringa, non può essere utilizzata per modificare il contenuto a cui punta. |
| crbegin() | Questa funzione restituisce un iteratore inverso costante che punta alla fine della stringa, non può essere utilizzata per modificare il contenuto a cui punta. |
| cred() | Questa funzione restituisce un iteratore inverso costante che punta al precedente dell'inizio della stringa, non può essere utilizzata per modificare il contenuto a cui punta. |
Algoritmo:
- Dichiarare una stringa
- Prova a ripetere la stringa utilizzando tutti i tipi di iteratori
- Prova la modifica dell'elemento della stringa.
- Visualizza tutte le iterazioni.
Esempio:
CPP
// C++ Program to demonstrate the working of> // begin(), end(), rbegin(), rend(), cbegin(), cend(), crbegin(), crend()> #include> #include // for string class> using> namespace> std;> > // Driver Code> int> main()> {> > // Initializing string`> > string str => 'geeksforgeeks'> ;> > > // Declaring iterator> > std::string::iterator it;> > > // Declaring reverse iterator> > std::string::reverse_iterator it1;> > cout < <> 'Str:'> <'
'; // Displaying string cout < < 'The string using forward iterators is : '; for (it = str.begin(); it != str.end(); it++){ if(it == str.begin()) *it='G'; cout < < *it; } cout < < endl; str = 'geeksforgeeks'; // Displaying reverse string cout < < 'The reverse string using reverse iterators is ' ': '; for (it1 = str.rbegin(); it1 != str.rend(); it1++){ if(it1 == str.rbegin()) *it1='S'; cout < < *it1; } cout < < endl; str = 'geeksforgeeks'; //Displaying String cout < <'The string using constant forward iterator is :'; for(auto it2 = str.cbegin(); it2!=str.cend(); it2++){ //if(it2 == str.cbegin()) *it2='G'; //here modification is NOT Possible //error: assignment of read-only location //As it is a pointer to the const content, but we can inc/dec-rement the iterator cout < <*it2; } cout < <'
'; str = 'geeksforgeeks'; //Displaying String in reverse cout < <'The reverse string using constant reverse iterator is :'; for(auto it3 = str.crbegin(); it3!=str.crend(); it3++){ //if(it2 == str.cbegin()) *it2='S'; //here modification is NOT Possible //error: assignment of read-only location //As it is a pointer to the const content, but we can inc/dec-rement the iterator cout < <*it3; } cout < <'
'; return 0; } //Code modified by Balakrishnan R (rbkraj000)> |
Produzione
Str:geeksforgeeks The string using forward iterators is : Geeksforgeeks The reverse string using reverse iterators is : Skeegrofskeeg The string using constant forward iterator is :geeksforgeeks The reverse string using constant reverse iterator is :skeegrofskeeg
Complessità temporale: O(1)
Complessità spaziale: O(n) dove n è la dimensione della stringa
4) Funzioni di manipolazione:
| Funzione | Definizione |
|---|---|
| copia(array di caratteri, len, pos) | Questa funzione copia la sottostringa nell'array di caratteri di destinazione menzionato nei suoi argomenti. Sono necessari 3 argomenti, l'array di caratteri di destinazione, la lunghezza da copiare e la posizione iniziale nella stringa per avviare la copia. |
| scambio() | Questa funzione scambia una stringa con un'altra |
Esempio:
CPP
// C++ Program to demonstrate the working of> // copy() and swap()> #include> #include // for string class> using> namespace> std;> > // Driver Code> int> main()> {> > // Initializing 1st string> > string str1 => 'geeksforgeeks is for geeks'> ;> > > // Declaring 2nd string> > string str2 => 'geeksforgeeks rocks'> ;> > > // Declaring character array> > char> ch[80];> > > // using copy() to copy elements into char array> > // copies 'geeksforgeeks'> > str1.copy(ch, 13, 0);> > > // Displaying char array> > cout < <> 'The new copied character array is : '> ;> > cout < < ch < < endl;> > > // Displaying strings before swapping> > cout < <> 'The 1st string before swapping is : '> ;> > cout < < str1 < < endl;> > cout < <> 'The 2nd string before swapping is : '> ;> > cout < < str2 < < endl;> > > // using swap() to swap string content> > str1.swap(str2);> > > // Displaying strings after swapping> > cout < <> 'The 1st string after swapping is : '> ;> > cout < < str1 < < endl;> > cout < <> 'The 2nd string after swapping is : '> ;> > cout < < str2 < < endl;> > > return> 0;> }> |
Produzione
The new copied character array is : geeksforgeeks The 1st string before swapping is : geeksforgeeks is for geeks The 2nd string before swapping is : geeksforgeeks rocks The 1st string after swapping is : geeksforgeeks rocks The 2nd string after swapping is : geeksforgeeks is for geeks
Devi leggere: Classe String C++ e sue applicazioni