最新消息:

VB_Python代码对照算法百题(011)

Python 少儿编程 1537浏览 0评论

VB_Python代码对照算法百题(011)

VB代码(2017年4月浙江)16.小王编写了一个实现文字查找替换功能的 VB 程序,运行界面如图所示。文本框 Text1 显示原文内容, Text2 中输入查找内容,Text3中输入替换内容,单击“全部替换”按钮 Command1 后,Text4 显示查找替换的结果, Text5 显示替换的次数,Text6显示“查找内容”在原文中的起始位置。实现上述功能的VB程序如下,但加框处代码有错,请改正。

VB_Python代码对照算法百题(011) 

Private Sub Command1Click()

Dim s As String, resule As String, pos As String

Dim count As Integer, i As Integer

i = 1

count = 0

result = ”

pos = ”

Do While i <= Len(Text1.Text)

    s = Mid(Text1.Text, i, Len(Text2.Text))

    If s = Text2.Text Then

        result = result + Text3.Text

        count = count + 1

        pos = pos + Str(count) ‘(1)

        i = i + Len(Text2.Text)

    Else

        result = result + Text2.Text ‘(2)

        i = i + 1

    End If

Loop

Text4.Text = result

Text5.Text = Str(count)

Text6.Text = pos

End Sub

参考答案:

(1)pos+str(i)

(2)result=result+mid(Text1.Text,i,1)

Python代码:

text1=’博客是一种个数的网络出版形式,博客已经得到广泛应用。’

text2=input(‘查找内容:’)

text3=input(‘替换为:’)

i=0

count=0

result=”

pos=”

while i<=len(text1)-1:

    s=text1[i:(i+len(text2))]

    if s==text2:

        result=result+text3

        count=count+1

        pos=pos+str(i)+’ ‘

        i=i+1

    else:

        result=result+text1[i]

        i=i+1

print(‘替换结果:’,result)

print(‘替换次数:’,str(count))

print(‘原文中的起始位置:’,pos)

VB_Python代码对照算法百题(011) Python代码运行结果:

查找内容:博客

替换为:Bolg

替换结果: Bolg客是一种个数的网络出版形式,Bolg客已经得到广泛应用。

替换次数: 2

原文中的起始位置: 0 15

VB_Python代码对照算法百题(011)

您必须 登录 才能发表评论!