sevenOfNine
sevenOfNine

Reputation: 1554

In which case System.UnicodeString.Format is used?

My environment is RADStudio XE4 Update1 on Windows 7 pro (32bit).

I found that in C++ Builder there is a System::UnicodeString::Format() static method.

Format() can be used as follows. However, the same thing can be carried out by using String().sprintf(), I think.

String str;

// --- (1) ---
str = String::Format(L"%2d, %2d, %2d", ARRAYOFCONST((10, 2, 3)));
ShowMessage(str); // 10, 2, 3

// --- (2) ---
str = String().sprintf(L"%2d, %2d, %2d", 10, 2, 3);
ShowMessage(str); // 10, 2, 3

My question is in which case the Format() is used better than by using other functions?

Is this just a matter of taste?

Upvotes: 3

Views: 2631

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598414

Internally, UnicodeString::Format() calls Sysutils::Format(), which is Delphi's formatting function. Remember that the majority of the RTL/VCL/FMX is written in Delphi, not C++.

Internally, UnicodeString::sprint() calls the C runtime's vsnwprintf() function instead.

Different frameworks, different interfaces, different formatting rules, similar results.

One benefit of using UnicodeString::Format() instead of UnicodeString::sprint() is that Format() performs type checking at runtime. If it detects a mismatch while comparing the formatting string to the input parameters, it will raise an exception. UnicodeString::sprintf() does not do that, it interprets the input values exactly as you specify in the formatting string, so if you get something wrong then you risk corrupting the output or outright crashing your code.

But, if you are careful with your parameters, the differences come down to a matter of taste. .

Upvotes: 5

Related Questions