I am not clear about the difference between the cstring library and the string library. As I understand it, the string header is, as the name implies, for string types, while cstring is for using its functions with char type.
I am not clear about the difference between the cstring library and the string library. As I understand it, the string header is, as the name implies, for string types, while cstring is for using its functions with char type.
The cstring
library (also accessible via string.h
) is a library imported from C. Since C is not an object-oriented language, it is focused on working with char*
fixes. Thus, we find functions such as:
strcpy
: Copy a text string strlen
: Length of a text string strcat
: Concatenates two text strings The string
library is typical of C ++. This library revolves around the class std::string
that comes to be the natural substitute of char*
. The advantages of using this class over char*
are several:
char buffer[500]
) char*
via function string.c_str()
The class% co_of%, simplifying a lot, what it does is encapsulate a pointer of type string
and manage its life cycle. It allows writing code faster, more secure since, for example, it prevents it from being written outside the memory reserved for this purpose, and more readable.
An example of readability:
char* charFunc(const char* cadena1, int numero)
{
size_t len = strlen(cadena1);
len += log10(numero) + 1; // Número de dígitos del número
len += 1; // Espacio para el caracter 'char* charFunc(const char* cadena1, int numero)
{
size_t len = strlen(cadena1);
len += log10(numero) + 1; // Número de dígitos del número
len += 1; // Espacio para el caracter '%pre%'
char* ptr = new char[](len);
if( ptr )
sprintf(ptr,"%s%d",cadena1,numero);
return ptr;
}
std::string stringFunc(const std::string& cadena1, int numero)
{
return cadena1 + std::to_string(numero);
}
int main()
{
// Versión char*
char* cadena1 = charFunc("Una prueba",10);
std::cout << cadena1 << '\n';
delete[] cadena1;
// Versión string
std::string cadena2 = stringFunc("Una prueba",10);
std::cout << cadena2 << '\n';
// No necesita delete
}
'
char* ptr = new char[](len);
if( ptr )
sprintf(ptr,"%s%d",cadena1,numero);
return ptr;
}
std::string stringFunc(const std::string& cadena1, int numero)
{
return cadena1 + std::to_string(numero);
}
int main()
{
// Versión char*
char* cadena1 = charFunc("Una prueba",10);
std::cout << cadena1 << '\n';
delete[] cadena1;
// Versión string
std::string cadena2 = stringFunc("Una prueba",10);
std::cout << cadena2 << '\n';
// No necesita delete
}
The cstring header has functions to handle C-style strings, functions such as strlen and strcpy
The string header provides the std :: string class and related functions and operators.
Headers have similar names, but they are not really related beyond that. They cover separate tasks.