2016-10-02 89 views

回答

-1

尝试

strString = "Smith" 
strleng=Len(strString) 
result="" 

if strleng<2 then 
    result=strString 
else 
    For i=1 To strleng 
    result= result& Mid(strString,i,1) 

    if i<>strleng then 
    result= result& "_" 
    end if 

    Next 
end if 
+0

为什么-1?此代码工作! – Esperento57

-1

或者:

Option Explicit 

' string concatenation (bad idea in languages with non-mutable strings) 
Function f1(s) 
    Dim l : l = Len(s) 
    If 2 > l Then 
    f1 = s 
    Else 
    Dim p 
    f1 = Left(s, 1) 
    For p = 2 To l 
     f1 = f1 & "_" & Mid(s, p, 1) 
    Next 
    End If 
End Function 

' Array via Mid(), Join 
Function s2a(s) 
    Dim l : l = Len(s) 
    ReDim a(l - 1) 
    Dim p 
    For p = 1 To l 
     a(p - 1) = Mid(s, p, 1) 
    Next 
    s2a = a 
End Function 
Function f2(s) 
    f2 = Join(s2a(s), "_") 
End Function 

' RegExp.Replace, Mid(,2) to get rid of first _ 
Function f3(s) 
    Dim r : Set r = New RegExp 
    r.Global = True 
    r.Pattern = "(.)" 
    f3 = Mid(r.Replace(s, "_$1"), 2) 
End Function 

Function qq(s) 
    qq = """" & s & """" 
End Function 

Dim s, t 
For Each s In Split(" a ab abc abcd Smith") 
    WScript.Echo "-----", qq(s) 
    t = f1(s) 
    WScript.Echo "  ", qq(t) 
    t = f2(s) 
    WScript.Echo "  ", qq(t) 
    t = f3(s) 
    WScript.Echo "  ", qq(t) 
Next 

输出:

cscript 39814484.vbs 
----- "" 
     "" 
     "" 
     "" 
----- "a" 
     "a" 
     "a" 
     "a" 
----- "ab" 
     "a_b" 
     "a_b" 
     "a_b" 
----- "abc" 
     "a_b_c" 
     "a_b_c" 
     "a_b_c" 
----- "abcd" 
     "a_b_c_d" 
     "a_b_c_d" 
     "a_b_c_d" 
----- "Smith" 
     "S_m_i_t_h" 
     "S_m_i_t_h" 
     "S_m_i_t_h"