要求函数的功能是:从参数str字符串中删除所有参数ch所指定的字符,返回实际删除字符的个数,删除后的字符串仍在str中,为此某人编写了函数DelChar如下: Function DelChar(str As String, ch As String) As

admin2020-04-18  24

问题 要求函数的功能是:从参数str字符串中删除所有参数ch所指定的字符,返回实际删除字符的个数,删除后的字符串仍在str中,为此某人编写了函数DelChar如下:
Function DelChar(str As String, ch As String) As Integer
    Dim n%, st$, c$
    st = ""
    n = 0
    For k = 1 To Len(str)
        c = Mid(str, k, 1)
        If c = ch Then
            st = st & c
        Else
            n = n + 1
        End If
    Next k
    str = st
    DelChar = n
End Function
并用下面的Command1_Click()过程观察函数调用结果
Private Sub Command1_Click()
    ch$ = Text1.Text
    Print DelChar(ch, "x"), ch
End Sub
发现结果有错误,程序代码需要修改,以下正确的修改方案是(    )。

选项 A、把语句If  c = ch  Then 改为If  c <> ch  Then
B、把语句Print DelChar(ch, "x"), ch改为Print DelChar(ch, "x") :Print ch
C、把语句DelChar = n 改为 DelChar = st
D、删掉语句str = st

答案A

解析 DelChar函数中,使用For循环,依次取出str字符串中的字符。然后通过if语句判断取出的字符是否为要删除的字符,若不是则将该字符保存到字符串变量st中,若是则将计数变量n的值加1。观察if条件判断语句可知,"If c = ch Then st = st & c else n=n+1"逻辑有错误,应该改为"If c <> ch Then st = st & c else n=n+1"。故选项A正确。
转载请注明原文地址:https://jikaoti.com/ti/swx0FFFM
0

最新回复(0)