本帖最后由 todaynew 于 2011-6-20 14:43 编辑
江羽版主最近在研究拼音声调字符转换为字母的问题,连续用了两种方法,其一是数组法,其二是字符串法。这个问题我也曾用过一个数据表法,说明解决此类问题的办法很多。结合这个问题,想讲一下Replace函数的嵌套问题。由于没有依赖其他的辅助手段,比较起来可以称之为裸奔法。
许多函数都是可以嵌套使用的,比如iif函数、instr函数等等。Replace函数也是可以嵌套使用的,Replace的嵌套执行的是连续的不同替换。只要你愿意可以嵌套很多层,不过为了阅读的方便起见,一般可以顺序的用几次Replace嵌套来解决替换问题。比如拼音声调字符转换为字母的问题,我们可以写如下自定义函数:
function str1(str0 as string) as string
'功能:将拼音声调字符转换为字母
str1=str0
str1=Replace(Replace(Replace(Replace(str1,"ā","a"),"á","a"),"ǎ","a"),"à","a")
str1=Replace(Replace(Replace(Replace(str1,"ē","e"),"é","e"),"ě","e"),"è","e")
str1=Replace(Replace(Replace(Replace(str1,"ī","i"),"í","i"),"ǐ","i"),"ì","i")
str1=Replace(Replace(Replace(Replace(str1,"ō","o"),"ó","o"),"ǒ","o"),"ò","o")
str1=Replace(Replace(Replace(Replace(str1,"ū","u"),"ú","u"),"ǔ","u"),"ù","u")
str1=Replace(Replace(Replace(Replace(str1,"ǖ","v"),"ǘ","v"),"ǚ","v"),"ǜ","v")
end function
这个函数的编制方法可以用到许多方面,如果你想将阿拉伯数字转换为中文数字,也是可以用此方法加以解决的,我们可以编写如下的自定义函数:
function str1(str0 as string,B as boolean) as string
'功能:将阿拉伯数转换为中文字符
'参数:B=true 转换为一、二... B=False 转换为壹、贰...
str1=str0
select case B
case true
str1=Replace(Replace(Replace(Replace(str1,"0","0"),"1","一"),"2","二"),"3","三")
str1=Replace(Replace(Replace(Replace(str1,"4","四"),"5","五"),"6","六"),"7","七")
str1=Replace(Replace(str1,"8","八"),"9","九")
case false
str1=Replace(Replace(Replace(Replace(str1,"0","零"),"1","壹"),"2","贰"),"3","叁")
str1=Replace(Replace(Replace(Replace(str1,"4","肆"),"5","伍"),"6","陆"),"7","柒")
str1=Replace(Replace(str1,"8","捌"),"9","玖")
end select
end function
假如你认为运算符输出不美观,也可以用这个方法来编写一个自定义的转换函数:
function str1(str0 as string) as string
'功能:将运算符转换为输出格式
str1=str0
str1=Replace(Replace(Replace(Replace(str1,"+","+"),"-","-"),"*","×"),"/","÷")
str1=Replace(Replace(Replace(Replace(str1,"=","="),"<>","≠"),"<=","≤"),">=","≥")
str1=Replace(Replace(str1,"<","<"),">",">")
end function
如此等等,你可以按照你的需要,依据此法写出很多实用功能很强的自定义函数来了。通过这个讲座,希望能使初学的版友明白,很多时候自定义函数就是一两句VB语句,关键看你是否真正掌握和理解了它们。掌握和理解了,就能在多种方法中找到最简单最直接的那些东西。
|