实际位置字符串格式

Real positional string formatting?

本文关键字:格式 字符串 位置      更新时间:2023-10-16

(注意:我知道Boost.Format,我正在寻找更好的方法来执行以下操作。
首先是一个用例示例:在某些国家/地区,您可以通过先称呼他/她的姓氏和姓氏来命名一个人,而在其他国家/地区则恰恰相反。

现在,对于我的代码,我目前通过以下方式使用 Boost.Format 解决此问题:

#include <boost/format.hpp>
#include <iostream>
#include <stdlib.h>
#include <utility>
int main(){
    using namespace boost;
    int pos1 = 2, pos2 = 1;
    char const* surname = "Surname", *forename = "Forename";
    // decision on ordering here
    bool some_condition = false;
    if(some_condition)
      std::swap(pos1,pos2);
    char buf[64];
    sprintf(buf,"Hello %c%d%c %c%d%c",'%',pos1,'%','%',pos2,'%');
    // buf == "Hello %[pos1]% %[pos2]%"; with [posN] = value of posN
    std::cout << format(buf) % surname % forename;
}

现在,我宁愿这样,即format行中的所有内容:

std::cout << format("Hello %%1%% %%2%%") % pos1 % pos2 % surname % forename;

但遗憾的是,这不起作用,因为我得到了一个很好的解析异常。

有没有具有真实位置格式的库?甚至是我不知道的Boost.Format实现这一目标的方法?

在我看来,Boost.Spirit.Karma是权威的现代输出格式库。

这是 Boost.Locale 的消息格式化部分,类似于 GNU gettext。

你会在其中写:

cout << format(translate("Hello {1} {2}!")) % forename % surname << endl;

然后翻译器将使用消息目录翻译字符串:

msgid "Hello {1} {2}!"
msgstr "こんにちは {2}-さん!"

我只是交换你插值的值

std::swap(surname, forename)

这样就可以完成了这项工作。如果你不想惹他们,有参考:

const std::string& param1(bSwapThem? forename : surname);
const std::string& param2(bSwapThem? surname  : forename);

听起来应该在系统区域设置中,但看起来目前不受支持。

简单的方法呢?

   if(some_condition)
      std::cout << surname << " " << forename;
   else
      std::cout << forename << " " << surname;

我会用?:

char const* surname = "Surname", *forename = "Forename";
bool swapFlag = (some_condition) ? true : false;
std::cout << "Hello " << (swapFlag ? surname : forename) << " " << (!swapFlag ? surname : forename) << std::endl;

您可以通过递归应用格式来执行此操作:

cout << format(str(format("%%%1%%% %%%2%%%") % pos1 % pos2)) % surname % forname;

但是,我建议使用像GNU gettext这样的东西。