1

我有一个值为“3D7H40M20S”的字符串,它应该转换为 3 天 7 小时 40 分钟和 20 秒”。这是我到目前为止尝试过的:

        BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
    AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("ScreeningSLAWaitTimeDuration");
    scrSlaWaitDur = (String)attr.getInputValue();
    System.out.println("-------------------------------------------SCREENING SLA WAIT DURATION---------------"+scrSlaWaitDur);
    scrSlaWaitDur = scrSlaWaitDur.substring(2, scrSlaWaitDur.length());
    System.out.println("--------------------------------------------SUBSTRING--------------------"+scrSlaWaitDur);
    int dIndex = scrSlaWaitDur.indexOf("D");
    System.out.println("*******************************************INDEX OF D**********************************"+dIndex);
    if(dIndex != -1){
        String newDur = scrSlaWaitDur.substring(0, dIndex)+" days "+scrSlaWaitDur.substring(dIndex+1);
        int mIndex = scrSlaWaitDur.lastIndexOf("M");
        String newDur2 = scrSlaWaitDur.substring(0, mIndex)+" minute "+scrSlaWaitDur.substring(mIndex+1);
        int sIndex = newDur2.lastIndexOf("S");
        String newDur3 = newDur2.substring(0,sIndex)+" second";
        scrSlaWaitDur = newDur3;
        return scrSlaWaitDur;
    }

我知道这很烦人而且很冗长。我可以以更简单的方式实现要求吗?

4

2 回答 2

2

一种务实的方法是替换单位令牌:

return scrSlaWaitDur.replace("D", " Days ").replace("H", " Hours ").replace("M", " Minutes ").replace("S", " Seconds");

输出:

3 Days 7 Hours 40 Minutes 20 Seconds
于 2013-10-24T16:02:33.653 回答
1

您可以在没有 index() 的情况下使用 substring(),即:

String result = 
scrSlaWaitDur.replace("D"," Days ").replace("H"," Hours ").replace("M"," Minutes ").replace("S"," Seconds");

但我确信有人会想出一个 fency 正则表达式解决方案。;-)

于 2013-10-24T16:03:41.870 回答