VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)

VB爱好者乐园(VBGood)

 找回密码
 立即注册
搜索
查看: 866|回复: 1

请教字符串替换的问题

[复制链接]
发表于 2021-6-17 14:39:25 | 显示全部楼层 |阅读模式
例如一个字符串“1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,16,17,18,19,20,”,我想Split后将第5个和第15个替换成0后生成新的字符串,我写的程序如下:

程序代码:
  1. Dim a As String
  2. Dim b() As String
  3. Dim temp1 As String
  4. Dim temp2 As String
  5. Dim i As Integer
  6. Dim c As String


  7. Private Sub Command1_Click()
  8. temp1 = ""
  9. b = Split(a, ",")
  10. b(5) = 0
  11. b(15) = 0
  12. For i = 0 To UBound(b) - 1
  13. temp1 = temp1 & b(i) & ","
  14. Next i
  15. Text1.Text = temp1
  16. End Sub

  17. Private Sub Command2_Click()
  18. temp2 = ""
  19. b = Split(a, ",")
  20. c = 0
  21. temp2 = Replace(a, b(5), c)
  22. Text2.Text = temp2
  23. End Sub

  24. Private Sub Form_Load()
  25. Text1.Text = ""
  26. Text2.Text = ""
  27. a = "1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,0,11,12,13,14,15,16,17,18,19,20,"
  28. End Sub
复制代码


Command1用循环方式生成新的字符串(结果正确),Command2用Replace替换(结果不对)。

想请教一下,生成新的字符串一定要用Command1方式循环得出吗?我的每个文件中类似的字符串有数万行,每行的UBound(b)没有规律且不一致,同时想处理数十到数百个文件,每行都做个循环生成新字符串然后重新写成新文件,似乎效率太低,有什么好办法吗?
发表于 2021-6-18 10:53:28 | 显示全部楼层
本帖最后由 cwa9958 于 2021-6-18 11:12 编辑

Replace函数

返回一个字符串,该字符串中指定的子字符串已被替换成另一子字符串

因为你的字符串a里的子字符串b(5)不只是一个,所有符合的都会被替换的,所以结果不对。
Private Sub Command1_Click()
temp1 = ""
b = Split(a, ",")
b(5) = 0
b(15) = 0
'For i = 0 To UBound(b) - 1
'temp1 = temp1 & b(i) & ","
'Next i
temp1 = Join(b, ",")
Text1.Text = temp1
End Sub

ps:你的这个好像是替换了第6个和第16个的。

也可以用replace函数做,但是有点繁琐,特别是要替换的相同字符串有多个,而且要求替换的是在后面的。

Private Sub Command3_Click()
    Dim n As Integer, m As Integer, m1 As Integer
    Dim a1 As String
   
    n = 5
    For i = 1 To n - 1
        m = InStr(m + 1, a, ",")
    Next
    m1 = InStr(m + 1, a, ",")
    a1 = Mid(a, m, m1 - m + 1)
   
    Text2 = Left(a, m) & Replace(a, a1, "0,", m, 1)
   
End Sub
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

文字版|手机版|小黑屋|VBGood  

GMT+8, 2021-9-23 01:34

VB爱好者乐园(VBGood)
快速回复 返回顶部 返回列表