String
Sitio: | Facultad de Ingeniería U.Na.M. |
Curso: | Computación ET-344 |
Libro: | String |
Imprimido por: | Invitado |
Día: | miércoles, 22 de enero de 2025, 08:55 |
Introducción
C++ por defecto solo soporta el tipo de datos "c-string" que como vimos es un arreglo de caracteres terminados en "\0".
Para poder trabajar con "string" se debe utilizar la librería estándar <string>
<string>
- string -> String class (class)
- u16string -> String of 16-bit characters (class)
- u32string -> String of 32-bit characters (class)
- wstring -> Wide string (class )
- length
- append
- copy
- find
- substr
- compare
- etc...
Método Compare
The compared string is the value of the string object or -if the signature used has a pos and a len parameters- the substring that begins at its character in position pos and spans len characters.
This string is compared to a comparing string, which is determined by the other arguments passed to the function.
// comparing apples with apples
#include <iostream>
#include <string>
int main ()
{
std::string str1 ("green apple");
std::string str2 ("red apple");
if (str1.compare(str2) != 0)
std::cout << str1 << " is not " << str2 << '\n';
if (str1.compare(6,5,"apple") == 0)
std::cout << "still, " << str1 << " is an apple\n";
if (str2.compare(str2.size()-5,5,"apple") == 0)
std::cout << "and " << str2 << " is also an apple\n";
if (str1.compare(6,5,str2,4,5) == 0)
std::cout << "therefore, both are apples\n";
return 0;
}
Método Find
When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences before pos.
Notice that it is enough for one single character of the sequence to match (not all of them). See string::find for a function that matches entire sequences.
// string::find_first_of
#include <iostream> // std::cout
#include <string> // std::string
#include <cstddef> // std::size_t
int main ()
{
std::string str ("Please, replace the vowels in this sentence by asterisks.");
std::size_t found = str.find_first_of("aeiou");
while (found!=std::string::npos)
{
str[found]='*';
found=str.find_first_of("aeiou",found+1);
}
std::cout << str << '\n';
return 0;
}
La salida sería:
Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.
Método Copy
// string::copy
#include <iostream>
#include <string>
int main ()
{
char buffer[20];
std::string str ("Test string...");
std::size_t length = str.copy(buffer,6,5);
buffer[length]='\0';
std::cout << "buffer contains: " << buffer << '\n';
return 0;
}
La salida sería:buffer contains: string
Método substr
The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).
// string::substr
#include <iostream>
#include <string>
int main ()
{
std::string str="We think in generalities, but we live in details.";
// (quoting Alfred N. Whitehead)
std::string str2 = str.substr (3,5); // "think"
std::size_t pos = str.find("live"); // position of "live" in str
std::string str3 = str.substr (pos); // get from "live" to the end
std::cout << str2 << ' ' << str3 << '\n';
return 0;
}
La salida sería:think live in details.
Método length
This is the number of actual bytes that conform the contents of the string, which is not necessarily equal to its storage capacity.
Note that string objects handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters (such as UTF-8).
Both string::size and string::length are synonyms and return the exact same value.
// string::length
#include <iostream>
#include <string>
int main ()
{
std::string str ("Test string");
std::cout << "The size of str is " << str.length() << " bytes.\n";
return 0;
}
The size of str is 11 bytes
Formas de adquirir texto
Existen varias formas de adquirir texto/caracteres desde archivos o ingreso por teclado. Por lo general los datos se extraen de un objeto que representa un flujo (stream). Recordemos que cin es un flujo de entrada.
- operador >> <istream>
- operador >> <string>
- get()
- getline() string
- getline() fstream