I
I
igorzash2018-06-11 10:53:44
C++ / C#
igorzash, 2018-06-11 10:53:44

What is the correct way to use strings in pluses?

What is the correct way to use strings in C++? Through the string construction in std, char[] or char*.
I have always used string, but I see other implementations very often.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2018-06-11
@igorzash

• std::string - Usually, unless otherwise noted.
• QString, AnsiString/UnicodeString and others - in their respective frameworks, usually very close to interface functions.
• char* - almost never used in real code. Mostly for optimization if there is native memory management. It happened somehow in its own XML parser (it works 2.5 times slower than the record holder, pugixml. But even this is many times faster than Excel, namespaces out of the box, memory consumption is scanty and programming is simple.
) its const counterpart.
• const char*. It can be a single const char* + a null-terminated string, or a pointer + length, or a pointer to start + pointer to end.
1. If it is expected that we will pass a string literal to the function.

void writeEnum(st::Stream& st, int value, const char* names[]) {}

enum class Letter { A, B, C, …, Z, NN };
const char* natoNames[static_cast<int>(Letter::NN)] = { "alpha", "bravo", "charlie", … };
writeEnum(someStream, static_cast<int>(Letter::E), natoName);

2. If an operation with a string can be performed "on the spot" without starting a new memory: (trim, as you know, trimming spaces at the beginning and end) 3. If the data structure parasitizes on other people's lines without starting its own memory. Especially if the string construction is unknown (for example, when passing data from plugin to plugin). 4. In libraries, if they are really so compact that there is no need to include bold STL. • char[] - only as an optimization when the string length limit is known and small.
wchar_t* myFtos(double value, wchar_t* buf, const FloatFormat& format) {}

wchar_t buf[100];
myFtos(100.500, buf, FloatFormat::NICE);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question