String

Sitio: Facultad de Ingeniería U.Na.M.
Curso: Computación ET-344
Libro: String
Imprimido por: Invitado
Día: miércoles, 3 de julio de 2024, 06:23

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 es un header de C++ (librería). Esta librería introduce el tipo string, tratamiento de caracteres y un grupo de funciones de conversión de texto.

Se pueden instanciar cuatro clases
  • string -> String class (class)
  • u16string -> String of 16-bit characters (class)
  • u32string -> String of 32-bit characters (class)
  • wstring -> Wide string (class )

La utilización de esta librería permite utilizar funciones (métodos) como:
  • length
  • append
  • copy
  • find
  • substr
  • compare
  • etc...
https://www.cplusplus.com/reference/string/string/

Método Compare

Compare strings
Compares the value of the string object (or a substring) to the sequence of characters specified by its arguments.

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

Find character in string
Searches the string for the first character that matches any of the characters specified in its arguments.

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.

Ejemplo:
// 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

Copy sequence of characters from string
Copies a substring of the current value of the string object into the array pointed by s. This substring contains the len characters that start at position pos.

// 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

Generate substring
Returns a newly constructed string object with its value initialized to a copy of a substring of this object.

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).
Ejemplo:
// 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

Return length of string
Returns the length of the string, in terms of bytes.

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.

Ejemplo:
// 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;
}

La salida sería:
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

operador >> <istream>