Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Should I use strings or char arrays, in general?

Tags:

c++

c

string

char

I'm a bit fuzzy on the basic ways in which programmers code differently in C and C++. One thing in particular is the usage of strings in C++ over char arrays, or vice versa. So, should I use strings or char arrays, in general, and why?

like image 214
physicsmichael Avatar asked Apr 16 '10 05:04

physicsmichael


People also ask

Should I use char array or string?

In C++ you should in almost all cases use std::string instead of a raw char array. std::string manages the underlying memory for you, which is by itself a good enough reason to prefer it.

Are char arrays faster than strings?

So the character array approach remains significantly faster although less so. In these tests, it was about 29% faster.

Are all char arrays C-strings?

C-strings are simply implemented as a char array which is terminated by a null character (aka 0 ). This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.

Are strings just char arrays?

Char arrays are mutable, Strings are not. Also, string is Array returns false, while char[] is Array returns true. Show activity on this post. No, it's not an array.


2 Answers

In C++ you should in almost all cases use std::string instead of a raw char array.

std::string manages the underlying memory for you, which is by itself a good enough reason to prefer it.

It also provides a much easier to use and more readable interface for common string operations, e.g. equality testing, concatenation, substring operations, searching, and iteration.

like image 143
James McNellis Avatar answered Nov 07 '22 09:11

James McNellis


If you're modifying or returning the string, use std::string. If not, accept your parameter as a const char* unless you absolutely need the std::string member functions. This makes your function usable not only with std::string::c_str() but also string literals. Why make your caller pay the price of constructing a std::string with heap storage just to pass in a literal?

like image 31
Ben Voigt Avatar answered Nov 07 '22 10:11

Ben Voigt