本文整理汇总了C++中MessageFormat::format方法的典型用法代码示例。如果您正苦于以下问题:C++ MessageFormat::format方法的具体用法?C++ MessageFormat::format怎么用?C++ MessageFormat::format使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MessageFormat
的用法示例。
在下文中一共展示了MessageFormat::format方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: pos
// {sfb} doesn't apply in C++?
void MessageFormatRegressionTest::Test4114739()
{
UErrorCode status = U_ZERO_ERROR;
MessageFormat *mf = new MessageFormat("<{0}>", status);
failure(status, "new MessageFormat");
Formattable *objs1 = NULL;
//Formattable objs2 [] = {};
//Formattable *objs3 [] = {NULL};
//try {
UnicodeString pat;
UnicodeString res;
logln("pattern: \"" + mf->toPattern(pat) + "\"");
log("format(null) : ");
FieldPosition pos(FieldPosition::DONT_CARE);
logln("\"" + mf->format(objs1, 0, res, pos, status) + "\"");
failure(status, "mf->format");
/*log("format({}) : ");
logln("\"" + mf->format(objs2, 0, res, FieldPosition(FieldPosition::DONT_CARE), status) + "\"");
failure(status, "mf->format");
log("format({null}) :");
logln("\"" + mf->format(objs3, 0, res, FieldPosition(FieldPosition::DONT_CARE), status) + "\"");
failure(status, "mf->format");*/
/*} catch (Exception e) {
errln("Exception thrown for null argument tests.");
}*/
delete mf;
}
示例2: formatErrorMessage
void formatErrorMessage(UErrorCode &realStatus, const UnicodeString& pattern, const Locale& theLocale,
UErrorCode inStatus0, /* statusString 1 */ const Locale &inCountry2, double currency3, // these numbers are the message arguments.
UnicodeString &result)
{
if(U_FAILURE(realStatus))
return; // you messed up
UnicodeString errString1(u_errorName(inStatus0));
UnicodeString countryName2;
inCountry2.getDisplayCountry(theLocale,countryName2);
Formattable myArgs[] = {
Formattable((int32_t)inStatus0), // inStatus0 {0}
Formattable(errString1), // statusString1 {1}
Formattable(countryName2), // inCountry2 {2}
Formattable(currency3)// currency3 {3,number,currency}
};
MessageFormat *fmt = new MessageFormat("MessageFormat's API is broken!!!!!!!!!!!",realStatus);
fmt->setLocale(theLocale);
fmt->applyPattern(pattern, realStatus);
if (U_FAILURE(realStatus)) {
delete fmt;
return;
}
FieldPosition ignore = 0;
fmt->format(myArgs,4,result,ignore,realStatus);
delete fmt;
}
示例3: testMsgFormatChoice
void TestMessageFormat::testMsgFormatChoice(/* char* par */)
{
logln("running TestMessageFormat::testMsgFormatChoice");
UErrorCode err = U_ZERO_ERROR;
MessageFormat* form = new MessageFormat("The disk \"{1}\" contains {0}.", err);
double filelimits[] = {0,1,2};
UnicodeString filepart[] = {"no files","one file","{0,number} files"};
ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3);
form->setFormat(1,*fileform); // NOT zero, see below
//is the format adopted?
FieldPosition ignore(FieldPosition::DONT_CARE);
UnicodeString string;
Formattable testArgs1[] = {(int32_t)0, "MyDisk"};
form->format(testArgs1, 2, string, ignore, err);
if (string != "The disk \"MyDisk\" contains no files.") {
errln("TestMessageFormat::testMsgFormatChoice failed on test #1");
}
ignore.setField(FieldPosition::DONT_CARE);
string.remove();
Formattable testArgs2[] = {(int32_t)1, "MyDisk"};
form->format(testArgs2, 2, string, ignore, err);
if (string != "The disk \"MyDisk\" contains one file.") {
errln("TestMessageFormat::testMsgFormatChoice failed on test #2");
}
ignore.setField(FieldPosition::DONT_CARE);
string.remove();
Formattable testArgs3[] = {(int32_t)1273, "MyDisk"};
form->format(testArgs3, 2, string, ignore, err);
if (string != "The disk \"MyDisk\" contains 1,273 files.") {
errln("TestMessageFormat::testMsgFormatChoice failed on test #3");
}
delete form;
delete fileform;
}
示例4: testSimpleFormat
void TestMessageFormat::testSimpleFormat(/* char* par */)
{
logln("running TestMessageFormat::testSimpleFormat");
UErrorCode err = U_ZERO_ERROR;
Formattable testArgs1[] = {(int32_t)0, "MyDisk"};
Formattable testArgs2[] = {(int32_t)1, "MyDisk"};
Formattable testArgs3[] = {(int32_t)12, "MyDisk"};
MessageFormat* form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).", err);
UnicodeString string;
FieldPosition ignore(FieldPosition::DONT_CARE);
form->format(testArgs1, 2, string, ignore, err);
if (U_FAILURE(err) || string != "The disk \"MyDisk\" contains 0 file(s).") {
errln(UnicodeString("TestMessageFormat::testSimpleFormat failed on test #1"));
}
ignore.setField(FieldPosition::DONT_CARE);
string.remove();
form->format(testArgs2, 2, string, ignore, err);
if (U_FAILURE(err) || string != "The disk \"MyDisk\" contains 1 file(s).") {
logln(string);
errln(UnicodeString("TestMessageFormat::testSimpleFormat failed on test #2")+string);
}
ignore.setField(FieldPosition::DONT_CARE);
string.remove();
form->format(testArgs3, 2, string, ignore, err);
if (U_FAILURE(err) || string != "The disk \"MyDisk\" contains 12 file(s).") {
errln(UnicodeString("TestMessageFormat::testSimpleFormat failed on test #3")+string);
}
delete form;
}
示例5: forParsing
void MessageFormatRegressionTest::Test4118594()
{
UErrorCode status = U_ZERO_ERROR;
const UBool possibleDataError = TRUE;
MessageFormat *mf = new MessageFormat("{0}, {0}, {0}", status);
failure(status, "new MessageFormat");
UnicodeString forParsing("x, y, z");
//Object[] objs = mf.parse(forParsing, new ParsePosition(0));
int32_t count = 0;
ParsePosition pp(0);
Formattable *objs = mf->parse(forParsing, pp, count);
UnicodeString pat;
logln("pattern: \"" + mf->toPattern(pat) + "\"");
logln("text for parsing: \"" + forParsing + "\"");
UnicodeString str;
if (objs[0].getString(str) != "z")
errln("argument0: \"" + objs[0].getString(str) + "\"");
mf->applyPattern("{0,number,#.##}, {0,number,#.#}", status);
failure(status, "mf->applyPattern", possibleDataError);
//Object[] oldobjs = {new Double(3.1415)};
Formattable oldobjs [] = {Formattable(3.1415)};
UnicodeString result;
FieldPosition pos(FieldPosition::DONT_CARE);
result = mf->format( oldobjs, 1, result, pos, status );
failure(status, "mf->format", possibleDataError);
pat.remove();
logln("pattern: \"" + mf->toPattern(pat) + "\"");
logln("text for parsing: \"" + result + "\"");
// result now equals "3.14, 3.1"
if (result != "3.14, 3.1")
dataerrln("result = " + result + " - " + u_errorName(status));
//Object[] newobjs = mf.parse(result, new ParsePosition(0));
int32_t count1 = 0;
pp.setIndex(0);
Formattable *newobjs = mf->parse(result, pp, count1);
// newobjs now equals {new Double(3.1)}
if (newobjs == NULL) {
dataerrln("Error calling MessageFormat::parse");
} else {
if (newobjs[0].getDouble() != 3.1)
errln( UnicodeString("newobjs[0] = ") + newobjs[0].getDouble());
}
delete [] objs;
delete [] newobjs;
delete mf;
}
示例6:
UnicodeString&
LocaleDisplayNamesImpl::appendWithSep(UnicodeString& buffer, const UnicodeString& src) const {
if (buffer.isEmpty()) {
buffer.setTo(src);
} else {
UnicodeString combined;
Formattable data[] = {
buffer,
src
};
FieldPosition fpos;
UErrorCode status = U_ZERO_ERROR;
separatorFormat->format(data, 2, combined, fpos, status);
if (U_SUCCESS(status)) {
buffer.setTo(combined);
}
}
return buffer;
}
示例7: sample
void TestMessageFormat::sample()
{
MessageFormat *form = 0;
UnicodeString buffer1, buffer2;
UErrorCode success = U_ZERO_ERROR;
form = new MessageFormat("There are {0} files on {1}", success);
if (U_FAILURE(success)) {
errln("Err: Message format creation failed");
logln("Sample message format creation failed.");
return;
}
UnicodeString abc("abc");
UnicodeString def("def");
Formattable testArgs1[] = { abc, def };
FieldPosition fieldpos(0);
assertEquals("format",
"There are abc files on def",
form->format(testArgs1, 2, buffer2, fieldpos, success));
assertSuccess("format", success);
delete form;
}
示例8: if
UnicodeString&
TimeUnitFormat::format(const Formattable& obj, UnicodeString& toAppendTo,
FieldPosition& pos, UErrorCode& status) const {
if (U_FAILURE(status)) {
return toAppendTo;
}
if (obj.getType() == Formattable::kObject) {
const UObject* formatObj = obj.getObject();
const TimeUnitAmount* amount = dynamic_cast<const TimeUnitAmount*>(formatObj);
if (amount != NULL){
Hashtable* countToPattern = fTimeUnitToCountToPatterns[amount->getTimeUnitField()];
double number;
const Formattable& amtNumber = amount->getNumber();
if (amtNumber.getType() == Formattable::kDouble) {
number = amtNumber.getDouble();
} else if (amtNumber.getType() == Formattable::kLong) {
number = amtNumber.getLong();
} else {
status = U_ILLEGAL_ARGUMENT_ERROR;
return toAppendTo;
}
UnicodeString count = fPluralRules->select(number);
#ifdef TMUTFMT_DEBUG
char result[1000];
count.extract(0, count.length(), result, "UTF-8");
std::cout << "number: " << number << "; format plural count: " << result << "\n";
#endif
MessageFormat* pattern = ((MessageFormat**)countToPattern->get(count))[fStyle];
Formattable formattable[1];
formattable[0].setDouble(number);
return pattern->format(formattable, 1, toAppendTo, pos, status);
}
}
status = U_ILLEGAL_ARGUMENT_ERROR;
return toAppendTo;
}
示例9: adjustForUsageAndContext
UnicodeString&
LocaleDisplayNamesImpl::localeDisplayName(const Locale& locale,
UnicodeString& result) const {
UnicodeString resultName;
const char* lang = locale.getLanguage();
if (uprv_strlen(lang) == 0) {
lang = "root";
}
const char* script = locale.getScript();
const char* country = locale.getCountry();
const char* variant = locale.getVariant();
UBool hasScript = uprv_strlen(script) > 0;
UBool hasCountry = uprv_strlen(country) > 0;
UBool hasVariant = uprv_strlen(variant) > 0;
if (dialectHandling == ULDN_DIALECT_NAMES) {
char buffer[ULOC_FULLNAME_CAPACITY];
do { // loop construct is so we can break early out of search
if (hasScript && hasCountry) {
ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", script, "_", country, (char *)0);
localeIdName(buffer, resultName);
if (!resultName.isBogus()) {
hasScript = FALSE;
hasCountry = FALSE;
break;
}
}
if (hasScript) {
ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", script, (char *)0);
localeIdName(buffer, resultName);
if (!resultName.isBogus()) {
hasScript = FALSE;
break;
}
}
if (hasCountry) {
ncat(buffer, ULOC_FULLNAME_CAPACITY, lang, "_", country, (char*)0);
localeIdName(buffer, resultName);
if (!resultName.isBogus()) {
hasCountry = FALSE;
break;
}
}
} while (FALSE);
}
if (resultName.isBogus() || resultName.isEmpty()) {
localeIdName(lang, resultName);
}
UnicodeString resultRemainder;
UnicodeString temp;
StringEnumeration *e = NULL;
UErrorCode status = U_ZERO_ERROR;
if (hasScript) {
resultRemainder.append(scriptDisplayName(script, temp));
}
if (hasCountry) {
appendWithSep(resultRemainder, regionDisplayName(country, temp));
}
if (hasVariant) {
appendWithSep(resultRemainder, variantDisplayName(variant, temp));
}
resultRemainder.findAndReplace(formatOpenParen, formatReplaceOpenParen);
resultRemainder.findAndReplace(formatCloseParen, formatReplaceCloseParen);
e = locale.createKeywords(status);
if (e && U_SUCCESS(status)) {
UnicodeString temp2;
char value[ULOC_KEYWORD_AND_VALUES_CAPACITY]; // sigh, no ULOC_VALUE_CAPACITY
const char* key;
while ((key = e->next((int32_t *)0, status)) != NULL) {
locale.getKeywordValue(key, value, ULOC_KEYWORD_AND_VALUES_CAPACITY, status);
keyDisplayName(key, temp);
temp.findAndReplace(formatOpenParen, formatReplaceOpenParen);
temp.findAndReplace(formatCloseParen, formatReplaceCloseParen);
keyValueDisplayName(key, value, temp2);
temp2.findAndReplace(formatOpenParen, formatReplaceOpenParen);
temp2.findAndReplace(formatCloseParen, formatReplaceCloseParen);
if (temp2 != UnicodeString(value, -1, US_INV)) {
appendWithSep(resultRemainder, temp2);
} else if (temp != UnicodeString(key, -1, US_INV)) {
UnicodeString temp3;
Formattable data[] = {
temp,
temp2
};
FieldPosition fpos;
status = U_ZERO_ERROR;
keyTypeFormat->format(data, 2, temp3, fpos, status);
appendWithSep(resultRemainder, temp3);
} else {
appendWithSep(resultRemainder, temp)
.append((UChar)0x3d /* = */)
.append(temp2);
}
}
delete e;
//.........这里部分代码省略.........
示例10: PatternTest
void TestMessageFormat::PatternTest()
{
Formattable testArgs[] = {
Formattable(double(1)), Formattable(double(3456)),
Formattable("Disk"), Formattable(UDate((int32_t)1000000000L), Formattable::kIsDate)
};
UnicodeString testCases[] = {
"Quotes '', '{', 'a' {0} '{0}'",
"Quotes '', '{', 'a' {0,number} '{0}'",
"'{'1,number,'#',##} {1,number,'#',##}",
"There are {1} files on {2} at {3}.",
"On {2}, there are {1} files, with {0,number,currency}.",
"'{1,number,percent}', {1,number,percent},",
"'{1,date,full}', {1,date,full},",
"'{3,date,full}', {3,date,full},",
"'{1,number,#,##}' {1,number,#,##}",
};
UnicodeString testResultPatterns[] = {
"Quotes '', '{', a {0} '{'0}",
"Quotes '', '{', a {0,number} '{'0}",
"'{'1,number,#,##} {1,number,'#'#,##}",
"There are {1} files on {2} at {3}.",
"On {2}, there are {1} files, with {0,number,currency}.",
"'{'1,number,percent}, {1,number,percent},",
"'{'1,date,full}, {1,date,full},",
"'{'3,date,full}, {3,date,full},",
"'{'1,number,#,##} {1,number,#,##}"
};
UnicodeString testResultStrings[] = {
"Quotes ', {, a 1 {0}",
"Quotes ', {, a 1 {0}",
"{1,number,#,##} #34,56",
"There are 3,456 files on Disk at 1/12/70 5:46 AM.",
"On Disk, there are 3,456 files, with $1.00.",
"{1,number,percent}, 345,600%,",
"{1,date,full}, Wednesday, December 31, 1969,",
"{3,date,full}, Monday, January 12, 1970,",
"{1,number,#,##} 34,56"
};
for (int32_t i = 0; i < 9; ++i) {
//it_out << "\nPat in: " << testCases[i]);
MessageFormat *form = 0;
UErrorCode success = U_ZERO_ERROR;
UnicodeString buffer;
form = new MessageFormat(testCases[i], Locale::getUS(), success);
if (U_FAILURE(success)) {
errln("MessageFormat creation failed.#1");
logln(((UnicodeString)"MessageFormat for ") + testCases[i] + " creation failed.\n");
continue;
}
if (form->toPattern(buffer) != testResultPatterns[i]) {
errln(UnicodeString("TestMessageFormat::PatternTest failed test #2, i = ") + i);
//form->toPattern(buffer);
errln(((UnicodeString)" Orig: ") + testCases[i]);
errln(((UnicodeString)" Exp: ") + testResultPatterns[i]);
errln(((UnicodeString)" Got: ") + buffer);
}
//it_out << "Pat out: " << form->toPattern(buffer));
UnicodeString result;
int32_t count = 4;
FieldPosition fieldpos(0);
form->format(testArgs, count, result, fieldpos, success);
if (U_FAILURE(success)) {
errln("MessageFormat failed test #3");
logln("TestMessageFormat::PatternTest failed test #3");
continue;
}
if (result != testResultStrings[i]) {
errln("TestMessageFormat::PatternTest failed test #4");
logln("TestMessageFormat::PatternTest failed #4.");
logln(UnicodeString(" Result: ") + result );
logln(UnicodeString(" Expected: ") + testResultStrings[i] );
}
//it_out << "Result: " << result);
#if 0
/* TODO: Look at this test and see if this is still a valid test */
logln("---------------- test parse ----------------");
form->toPattern(buffer);
logln("MSG pattern for parse: " + buffer);
int32_t parseCount = 0;
Formattable* values = form->parse(result, parseCount, success);
if (U_FAILURE(success)) {
errln("MessageFormat failed test #5");
logln(UnicodeString("MessageFormat failed test #5 with error code ")+(int32_t)success);
} else if (parseCount != count) {
errln("MSG count not %d as expected. Got %d", count, parseCount);
}
UBool failed = FALSE;
for (int32_t j = 0; j < parseCount; ++j) {
if (values == 0 || testArgs[j] != values[j]) {
//.........这里部分代码省略.........
示例11: sizeof
/*
* This method updates the cache and must be called with a lock
*/
const UChar*
TZGNCore::getPartialLocationName(const UnicodeString& tzCanonicalID,
const UnicodeString& mzID, UBool isLong, const UnicodeString& mzDisplayName) {
U_ASSERT(!tzCanonicalID.isEmpty());
U_ASSERT(!mzID.isEmpty());
U_ASSERT(!mzDisplayName.isEmpty());
PartialLocationKey key;
key.tzID = ZoneMeta::findTimeZoneID(tzCanonicalID);
key.mzID = ZoneMeta::findMetaZoneID(mzID);
key.isLong = isLong;
U_ASSERT(key.tzID != NULL && key.mzID != NULL);
const UChar* uplname = (const UChar*)uhash_get(fPartialLocationNamesMap, (void *)&key);
if (uplname != NULL) {
return uplname;
}
UnicodeString location;
UnicodeString usCountryCode;
ZoneMeta::getCanonicalCountry(tzCanonicalID, usCountryCode);
if (!usCountryCode.isEmpty()) {
char countryCode[ULOC_COUNTRY_CAPACITY];
U_ASSERT(usCountryCode.length() < ULOC_COUNTRY_CAPACITY);
int32_t ccLen = usCountryCode.extract(0, usCountryCode.length(), countryCode, sizeof(countryCode), US_INV);
countryCode[ccLen] = 0;
UnicodeString regionalGolden;
fTimeZoneNames->getReferenceZoneID(mzID, countryCode, regionalGolden);
if (tzCanonicalID == regionalGolden) {
// Use country name
fLocaleDisplayNames->regionDisplayName(countryCode, location);
} else {
// Otherwise, use exemplar city name
fTimeZoneNames->getExemplarLocationName(tzCanonicalID, location);
}
} else {
fTimeZoneNames->getExemplarLocationName(tzCanonicalID, location);
if (location.isEmpty()) {
// This could happen when the time zone is not associated with a country,
// and its ID is not hierarchical, for example, CST6CDT.
// We use the canonical ID itself as the location for this case.
location.setTo(tzCanonicalID);
}
}
UErrorCode status = U_ZERO_ERROR;
UnicodeString name;
FieldPosition fpos;
Formattable param[] = {
Formattable(location),
Formattable(mzDisplayName)
};
fFallbackFormat->format(param, 2, name, fpos, status);
if (U_FAILURE(status)) {
return NULL;
}
uplname = fStringPool.get(name, status);
if (U_SUCCESS(status)) {
// Add the name to cache
PartialLocationKey* cacheKey = (PartialLocationKey *)uprv_malloc(sizeof(PartialLocationKey));
if (cacheKey != NULL) {
cacheKey->tzID = key.tzID;
cacheKey->mzID = key.mzID;
cacheKey->isLong = key.isLong;
uhash_put(fPartialLocationNamesMap, (void *)cacheKey, (void *)uplname, &status);
if (U_FAILURE(status)) {
uprv_free(cacheKey);
} else {
// put the name to the local trie as well
GNameInfo *nameinfo = (ZNameInfo *)uprv_malloc(sizeof(GNameInfo));
if (nameinfo != NULL) {
nameinfo->type = isLong ? UTZGNM_LONG : UTZGNM_SHORT;
nameinfo->tzID = key.tzID;
fGNamesTrie.put(uplname, nameinfo, status);
}
}
}
}
return uplname;
}
示例12: pattern1
void MessageFormatRegressionTest::Test4031438()
{
UErrorCode status = U_ZERO_ERROR;
UnicodeString pattern1("Impossible {1} has occurred -- status code is {0} and message is {2}.");
UnicodeString pattern2("Double '' Quotes {0} test and quoted '{1}' test plus 'other {2} stuff'.");
MessageFormat *messageFormatter = new MessageFormat("", status);
failure(status, "new MessageFormat");
const UBool possibleDataError = TRUE;
//try {
logln("Apply with pattern : " + pattern1);
messageFormatter->applyPattern(pattern1, status);
failure(status, "messageFormat->applyPattern");
//Object[] params = {new Integer(7)};
Formattable params []= {
Formattable((int32_t)7)
};
UnicodeString tempBuffer;
FieldPosition pos(FieldPosition::DONT_CARE);
tempBuffer = messageFormatter->format(params, 1, tempBuffer, pos, status);
if(tempBuffer != "Impossible {1} has occurred -- status code is 7 and message is {2}." || failure(status, "MessageFormat::format"))
dataerrln("Tests arguments < substitution failed");
logln("Formatted with 7 : " + tempBuffer);
ParsePosition pp(0);
int32_t count = 0;
Formattable *objs = messageFormatter->parse(tempBuffer, pp, count);
//if(objs[7/*params.length*/] != NULL)
// errln("Parse failed with more than expected arguments");
NumberFormat *fmt = 0;
UnicodeString temp, temp1;
for (int i = 0; i < count; i++) {
// convert to string if not already
Formattable obj = objs[i];
temp.remove();
if(obj.getType() == Formattable::kString)
temp = obj.getString(temp);
else {
fmt = NumberFormat::createInstance(status);
switch (obj.getType()) {
case Formattable::kLong: fmt->format(obj.getLong(), temp); break;
case Formattable::kInt64: fmt->format(obj.getInt64(), temp); break;
case Formattable::kDouble: fmt->format(obj.getDouble(), temp); break;
default: break;
}
}
// convert to string if not already
Formattable obj1 = params[i];
temp1.remove();
if(obj1.getType() == Formattable::kString)
temp1 = obj1.getString(temp1);
else {
fmt = NumberFormat::createInstance(status);
switch (obj1.getType()) {
case Formattable::kLong: fmt->format(obj1.getLong(), temp1); break;
case Formattable::kInt64: fmt->format(obj1.getInt64(), temp1); break;
case Formattable::kDouble: fmt->format(obj1.getDouble(), temp1); break;
default: break;
}
}
//if (objs[i] != NULL && objs[i].getString(temp1) != params[i].getString(temp2)) {
if (temp != temp1) {
errln("Parse failed on object " + objs[i].getString(temp1) + " at index : " + i);
}
}
delete fmt;
delete [] objs;
// {sfb} does this apply? no way to really pass a null Formattable,
// only a null array
/*tempBuffer = messageFormatter->format(null, tempBuffer, FieldPosition(FieldPosition::DONT_CARE), status);
if (tempBuffer != "Impossible {1} has occurred -- status code is {0} and message is {2}." || failure(status, "messageFormat->format"))
errln("Tests with no arguments failed");
logln("Formatted with null : " + tempBuffer);*/
logln("Apply with pattern : " + pattern2);
messageFormatter->applyPattern(pattern2, status);
failure(status, "messageFormatter->applyPattern", possibleDataError);
tempBuffer.remove();
tempBuffer = messageFormatter->format(params, 1, tempBuffer, pos, status);
if (tempBuffer != "Double ' Quotes 7 test and quoted {1} test plus other {2} stuff.")
dataerrln("quote format test (w/ params) failed. - %s", u_errorName(status));
logln("Formatted with params : " + tempBuffer);
/*tempBuffer = messageFormatter->format(null);
if (!tempBuffer.equals("Double ' Quotes {0} test and quoted {1} test plus other {2} stuff."))
errln("quote format test (w/ null) failed.");
logln("Formatted with null : " + tempBuffer);
logln("toPattern : " + messageFormatter.toPattern());*/
/*} catch (Exception foo) {
errln("Exception when formatting in bug 4031438. "+foo.getMessage());
}*/
//.........这里部分代码省略.........
示例13: fpos
void
TestChoiceFormat::TestComplexExample( void )
{
UErrorCode status = U_ZERO_ERROR;
const double filelimits[] = {-1, 0,1,2};
const UnicodeString filepart[] = {"are corrupted files", "are no files","is one file","are {2} files"};
ChoiceFormat* fileform = new ChoiceFormat( filelimits, filepart, 4);
if (!fileform) {
it_errln("*** test_complex_example fileform");
return;
}
Format* filenumform = NumberFormat::createInstance( status );
if (!filenumform) {
dataerrln((UnicodeString)"*** test_complex_example filenumform - " + u_errorName(status));
delete fileform;
return;
}
if (!chkstatus( status, "*** test_simple_example filenumform" )) {
delete fileform;
delete filenumform;
return;
}
//const Format* testFormats[] = { fileform, NULL, filenumform };
//pattform->setFormats( testFormats, 3 );
MessageFormat* pattform = new MessageFormat("There {0} on {1}", status );
if (!pattform) {
it_errln("*** test_complex_example pattform");
delete fileform;
delete filenumform;
return;
}
if (!chkstatus( status, "*** test_complex_example pattform" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
pattform->setFormat( 0, *fileform );
pattform->setFormat( 2, *filenumform );
Formattable testArgs[] = {(int32_t)0, "Disk_A", (int32_t)0};
UnicodeString str;
UnicodeString res1, res2;
pattform->toPattern( res1 );
it_logln("MessageFormat toPattern: " + res1);
fileform->toPattern( res1 );
it_logln("ChoiceFormat toPattern: " + res1);
if (res1 == "-1#are corrupted files|0#are no files|1#is one file|2#are {2} files") {
it_logln("toPattern tested!");
}else{
it_errln("*** ChoiceFormat to Pattern result!");
}
FieldPosition fpos(FieldPosition::DONT_CARE);
UnicodeString checkstr[] = {
"There are corrupted files on Disk_A",
"There are no files on Disk_A",
"There is one file on Disk_A",
"There are 2 files on Disk_A",
"There are 3 files on Disk_A"
};
// if (status != U_ZERO_ERROR) return; // TODO: analyze why we have such a bad bail out here!
if (U_FAILURE(status)) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
int32_t i;
int32_t start = -1;
for (i = start; i < 4; ++i) {
str = "";
status = U_ZERO_ERROR;
testArgs[0] = Formattable((int32_t)i);
testArgs[2] = testArgs[0];
res2 = pattform->format(testArgs, 3, str, fpos, status );
if (!chkstatus( status, "*** test_complex_example format" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
it_logln(i + UnicodeString(" -> ") + res2);
if (res2 != checkstr[i - start]) {
it_errln("*** test_complex_example res string");
it_errln(UnicodeString("*** ") + i + UnicodeString(" -> '") + res2 + UnicodeString("' unlike '") + checkstr[i] + UnicodeString("' ! "));
}
}
//.........这里部分代码省略.........
示例14: TestRBNF
// test RBNF extensions to message format
void TestMessageFormat::TestRBNF(void) {
// WARNING: this depends on the RBNF formats for en_US
Locale locale("en", "US", "");
UErrorCode ec = U_ZERO_ERROR;
UnicodeString values[] = {
// decimal values do not format completely for ordinal or duration, and
// do not always parse, so do not include them
"0", "1", "12", "100", "123", "1001", "123,456", "-17",
};
int32_t values_count = sizeof(values)/sizeof(values[0]);
UnicodeString formats[] = {
"There are {0,spellout} files to search.",
"There are {0,spellout,%simplified} files to search.",
"The bogus spellout {0,spellout,%BOGUS} files behaves like the default.",
"This is the {0,ordinal} file to search.", // TODO fix bug, ordinal does not parse
"Searching this file will take {0,duration} to complete.",
"Searching this file will take {0,duration,%with-words} to complete.",
};
int32_t formats_count = sizeof(formats)/sizeof(formats[0]);
Formattable args[1];
NumberFormat* numFmt = NumberFormat::createInstance(locale, ec);
if (U_FAILURE(ec)) {
dataerrln("Error calling NumberFormat::createInstance()");
return;
}
for (int i = 0; i < formats_count; ++i) {
MessageFormat* fmt = new MessageFormat(formats[i], locale, ec);
logln((UnicodeString)"Testing format pattern: '" + formats[i] + "'");
for (int j = 0; j < values_count; ++j) {
ec = U_ZERO_ERROR;
numFmt->parse(values[j], args[0], ec);
if (U_FAILURE(ec)) {
errln((UnicodeString)"Failed to parse test argument " + values[j]);
} else {
FieldPosition fp(0);
UnicodeString result;
fmt->format(args, 1, result, fp, ec);
logln((UnicodeString)"value: " + toString(args[0]) + " --> " + result + UnicodeString(" ec: ") + u_errorName(ec));
if (i != 3) { // TODO: fix this, for now skip ordinal parsing (format string at index 3)
int32_t count = 0;
Formattable* parseResult = fmt->parse(result, count, ec);
if (count != 1) {
errln((UnicodeString)"parse returned " + count + " args");
} else if (parseResult[0] != args[0]) {
errln((UnicodeString)"parsed argument " + toString(parseResult[0]) + " != " + toString(args[0]));
}
delete []parseResult;
}
}
}
delete fmt;
}
delete numFmt;
}
示例15: PluralFormatExample
static void PluralFormatExample() {
u_printf("=============================================================================\n");
u_printf(" PluralFormatExample()\n");
u_printf("\n");
u_printf(" Use PluralFormat and Messageformat to get Plural Form for languages below:\n");
u_printf(" English, Slovenian\n");
u_printf("=============================================================================\n");
//! [PluralFormatExample]
UErrorCode status =U_ZERO_ERROR;
Locale locEn = Locale("en");
Locale locSl = Locale("sl");
UnicodeString patEn = UnicodeString("one{dog} other{dogs}"); // English 'dog'
UnicodeString patSl = UnicodeString("one{pes} two{psa} few{psi} other{psov}"); // Slovenian translation of dog in Plural Form
// Create a new PluralFormat for a given locale locale and pattern string
PluralFormat plfmtEn = PluralFormat(locEn, patEn,status);
PluralFormat plfmtSl = PluralFormat(locSl, patSl,status);
// Constructs a MessageFormat for given pattern and locale.
MessageFormat* msgfmtEn = new MessageFormat("{0,number} {1}", locEn,status);
MessageFormat* msgfmtSl = new MessageFormat("{0,number} {1}", locSl,status);
int numbers[] = {0, 1, 2, 3, 4, 5, 10, 100, 101, 102};
u_printf("Output by using PluralFormat and MessageFormat API\n");
u_printf("%-16s%-16s%-16s\n","Number", "English","Slovenian");
// Use MessageFormat.format () to format the objects and append to the given StringBuffer
for (int i=0;i<sizeof(numbers)/sizeof(int);i++) {
UnicodeString msgEn,msgSl;
FieldPosition fpos = 0;
Formattable argEn[]={Formattable(numbers[i]), Formattable(plfmtEn.format(numbers[i],status))};
Formattable argSl[]={Formattable(numbers[i]), Formattable(plfmtSl.format(numbers[i],status))};
msgfmtEn->format(argEn,2,msgEn,fpos,status);
msgfmtSl->format(argSl,2,msgSl,fpos,status);
u_printf("%-16d%-16S%-16S\n", numbers[i], msgEn.getTerminatedBuffer(),msgSl.getTerminatedBuffer());
}
u_printf("\n");
// Equivalent code with message format pattern
UnicodeString msgPatEn = "{0,plural, one{# dog} other{# dogs}}";
UnicodeString msgPatSl = "{0,plural, one{# pes} two{# psa} few{# psi} other{# psov}}";
MessageFormat* altMsgfmtEn = new MessageFormat(msgPatEn, locEn,status);
MessageFormat* altMsgfmtSl = new MessageFormat(msgPatSl, locSl,status);
u_printf("Same Output by using MessageFormat API only\n");
u_printf("%-16s%-16s%-16s\n","Number", "English","Slovenian");
for (int i=0;i<sizeof(numbers)/sizeof(int);i++) {
UnicodeString msgEn,msgSl;
Formattable arg[] = {numbers[i]};
FieldPosition fPos =0;
altMsgfmtEn->format(arg, 1, msgEn, fPos, status);
altMsgfmtSl->format(arg, 1, msgSl, fPos,status);
u_printf("%-16d%-16S%-16S\n", numbers[i], msgEn.getTerminatedBuffer(), msgSl.getTerminatedBuffer());
}
delete msgfmtEn;
delete msgfmtSl;
delete altMsgfmtEn;
delete altMsgfmtSl;
//! [PluralFormatExample]
/* output of the sample code:
********************************************************************
Number English Slovenian
0 0 dogs 0 psov
1 1 dog 1 pes
2 2 dogs 2 psa
3 3 dogs 3 psi
4 4 dogs 4 psi
5 5 dogs 5 psov
10 10 dogs 10 psov
100 100 dogs 100 psov
101 101 dogs 101 pes
102 102 dogs 102 psa
*********************************************************************/
}