cyt
以前曾经写过一个类型安全的format输出,(见http://www.cppblog.com/cyt/archive/2005/10/08/578.html)。
今天又在codeporject里面发现有类似的CFormat(http://www.codeproject.com/useritems/pja_format.asp)。不过同样是那一句,很多人还是建议使用boost。不过本人老觉得boost那套东西性能有些问题,而且想把format独立出来使用基本上不可能,所以一直以来还是使用自己写的那个format_stream和format_string。
自己写的format_string在输出百分比的数据的时候有问题,理由是没有在‘%’后面加参数,所以没办法识别‘%’是占位符还是真正的‘%’号。虽然程序简单的把‘%%’认为是一个‘%’号。但是要输出百分数的时候如果写 "%%%"的话,则优先把前面的‘%%’变成了‘%’号了。我曾经把程序简单修改为碰到三个‘%’的时候,就视第一个为占位符,后面两个就合在一起变为‘%’号了。但始终在解释的时候有些怪怪的。例如连续四个‘%’,五个呢?后来,我就更干脆不改,所有输出百分数的时候一律写:str.format("percent: %").arg( nPercent, '%').str();
另外一个麻烦的就是输出16进制数的时候,那个argWithFormat参数也太多了点,有时候想简单输出一下都要填半天参数,估计参考CFormat的Hex实现也是一个不错的选择。反正只要能支持 << 操作的对象都能用在format_string里面。
format_stream/format_string的确是目前开发中用得最多的类。不过有时候讨论起来,为什么非要用format方式,难道就是因为好看的原因?前几天在看i18n,终于看到一个format_xxxx的优势:输出字符串的替换明显工作量少了很多很多。

在用javascript开发的日子,还是忘不了 format_xxxxx,于是有写了个javascript的版本:

function _formatString( strFormat ) {
    
this.format( strFormat );
}
;

_formatString.prototype.format 
= function ( strPattern ) {
    
this._pattern = strPattern;
    
this._p = 0;
    
this._res = "";
}
;

_formatString.prototype._moveToNext 
= function () {
    
for ( ; this._p < this._pattern.length; ++this._p ) {
        
var ch = this._pattern.charAt( this._p );
        
if ( ch == "%" ) {
            
++this._p;
            
if ( this._p < this._pattern.length && this._pattern.charAt( this._p ) == "%" ) {
                
this._res += "%";
            }
 else {
                
break;
            }
    
        }

        
else
            
this._res += ch;
    }

    
return this;
}
;

_formatString.prototype.str 
= function () {
    
this._res += this._pattern.substr( this._p );
    
return this._res;
}
;

function fmt( strPattern ) {
    
return new _formatString( strPattern );
}
;

_formatString.prototype.a 
= function () {
    
this._moveToNext();
    
for (var i = 0; i < arguments.length; i++{
        
this._res += arguments[i];
    }
  
    
return this;
}


_formatString.prototype.s 
= function () {
    
return this.str();
}

用起来大概就是:

var width = 400;
var height = 340;
var left = (screen.availWidth - width) / 2;
var top  = (screen.availHeight - height) / 2;
window.open('RYFL_lx.jsp', null,  fmt( 'width=%,height=%,left=%,top=%').a(width).a(height).a(left).a(top).s() ); 
posted on 2006-03-02 16:17 cyt 阅读(1090) 评论(0)  编辑 收藏 引用 所属分类: Work

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理