+ 6

C string or C++ string?

char c[] = "string"; //C std::string cpp = "string"; //C++ When to use C string and C++ string? What's the advantage?

27th Jul 2019, 1:03 PM
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż - avatar
1 Answer
+ 4
An std::string is a class which contains a cstring as well as attributes and methods to operate on that string. http://www.cplusplus.com/reference/string/string/ A cstring is, of course, just an array of characters, and is null-terminated. If you need a string without any need for its size, for getting a substring out of it, searching for a particular sequence of character in it, or to perform regex operations on it, then by all means feel free to use cstring. Else, for the sake of your time and sanity you might want to go for std::string. In terms of performance, the overhead of having a class manage the string for you doesn't really make std::string any slower than a raw cstring. This is a whole other story just in case you want to read into it: https://stackoverflow.com/questions/12124263/efficiency-of-c-string-vs-cstrings
27th Jul 2019, 1:28 PM
Hatsy Rei
Hatsy Rei - avatar