Skip to content

Instantly share code, notes, and snippets.

@catamorphism
Created November 12, 2025 22:37
Show Gist options
  • Select an option

  • Save catamorphism/6e4f052be2ae4cf9ae82f441426e8947 to your computer and use it in GitHub Desktop.

Select an option

Save catamorphism/6e4f052be2ae4cf9ae82f441426e8947 to your computer and use it in GitHub Desktop.
MessageFormat example with ICU 78
#define U_DISABLE_RENAMING 1
#include <unicode/messageformat2.h>
#include <iostream>
#include <unicode/unistr.h>
#include <unicode/ustream.h>
using namespace std;
using namespace icu;
using namespace message2;
bool testMessageFormat() {
UErrorCode errorCode = U_ZERO_ERROR;
UParseError parseError;
MessageFormatter::Builder builder(errorCode);
MessageFormatter mf = builder.setPattern(u".input {$userNumber :number} .match $userNumber * {{Hello, {$userNumber}!}}", parseError, errorCode)
.build(errorCode);
if (U_FAILURE(errorCode)) {
cout << "Syntax failed: ";
cout << u_errorName(errorCode);
}
std::map<UnicodeString, message2::Formattable> argMap;
argMap["userNumber"] = message2::Formattable(42.0);
MessageArguments args(argMap, errorCode);
if (U_FAILURE(errorCode)) {
cout << "Constructing args map failed: ";
cout << u_errorName(errorCode);
}
UnicodeString result = mf.formatToString(args, errorCode);
if (U_FAILURE(errorCode)) {
cout << "Formatting failed: ";
cout << u_errorName(errorCode);
}
UnicodeString expected("Hello, 42!");
u16string_view expectedS(expected);
u16string_view resultS(result);
if (result != expected) {
cout << "Wrong result! Expected: ";
cout << expected;
cout << "Got: ";
cout << result;
}
return (result == expected);
}
int main() {
return testMessageFormat() ? 0 : 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment