Strings in C are simply arrays of
char values - or in other words, a contiguous block of memory containing
chars. C++ inherits that representation, but also provides a safer and easier-to-use option called
std::string. In C++, the old C-style strings are often called C-Strings.
Most C++ gurus would advise you to avoid C-Strings and just use
std::string. And it is true that
std::string is safer and easier to use than C-Strings. Whereas
std::string manages memory for you and has a ton of built-in functionality, C-Strings are essentially just blocks of
char memory that you must manipulate with error-prone and inconsistent functions.
However, avoiding C-Strings entirely is difficult - sometimes you inherit code that’s using them, sometimes SDKs or libraries require you to use them, sometimes they are the most efficient option.
C-Strings can be confusing to work with. There are a variety of functions used to manipulate C-Strings, but some are deprecated or insecure, some are only available in certain compilers, and some have intricate ins and outs for using them properly.
So, my goal with this post is to catalogue some common operations you’d want to perform on C-Strings and identify the best options available, what to avoid, and what pitfalls exist.[Read More]