+ 1
which way of using string in c++ is better: an array of chars or string library?
6 Respuestas
+ 3
Avoid char arrays/pointers as much as you can. Almost all use cases of heap allocated C-strings are covered by std::string (with small strings there might even be no heap allocation at all, and almost all use cases of constant non-copying C-strings are covered by std::string_view.
If you want a dynamically allocated string that you own, use std::string. If you want a constant string that you want to recieve as arguments or pass around to functions and objects, use std::string_view. Use char arrays only if both those options aren't viable for some reason.
See std::string_view
https://en.cppreference.com/w/cpp/string/basic_string_view
Runtime Terror
I believe you wanted to write
std::string.c_str()
instead of
std::string.to_str()
+ 2
Depends on requirements choose according to characteristics considering :
*) When there is special library for string then why you want to use character array which does not provide many inbuilt functions which compare to string library..!
*) Arrays are static in nature so faster but need memory preallocated where as strings are dynamic in nature so slower than array..
edit:
and more clearly, hope link will helps.
https://www.geeksforgeeks.org/stdstring-class-in-c/amp/
+ 1
In modern c++, don't even think of using the chararacter array for strings... I've not been using them in any professional project for years.
When there's a C library that requires a char* or const char*
You can easily pass in a STL string as
std::string.c_str()
Or
std::string.data()
Trust me the implementation is fast just like using a normal array. Nothing special
+ 1
Better for what purpose exactly?
If you need character sorting or categorization, of course you will consider strings as arrays of characters;
If you need to work with strings as whole words or whole sentences, then you will consider to use strings only as strings, and not as characters;
It really varies by what purpose you want to give to your program.
Not sure if this is the type of answer you were searching for.
0
thanks!
0
XXX exactly... Now fixed