2012年1月2日 星期一

取代字串

讀入任意長度字串(最多50字元),對此字串坐下列處理動作:
(1) 列印出字串長度(使用者輸入的部分)。
(2) 以一個"4*號"字串取代每一個4字母單字,
(3) 以一個"3+號"字串取代每一個3字母單字,
(4) 以一個"5?號"字串取代每一個5字母單字,
並列印新字串。

輸入範例:

Enernet 5-4-3原則

輸出範例:
(1):15
(2):Enernet 5-4*號-3原則
(3):Enernet 5-4-3+號原則
(4): Enernet 5?號-4-3原則

5 則留言:

  1. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Dim ans2, ans3, ans4 As String
    Input #1, x
    ans1 = Len(x)
    Print #2, "(1):" & ans1

    For i = 1 To ans1
    a1 = Mid(x, i, 1)
    a2 = Mid(x, i, 1)
    a3 = Mid(x, i, 1)

    If a1 = 4 Then a1 = "4*號"
    ans2 = ans2 & a1
    If a2 = 3 Then a2 = "3+號"
    ans3 = ans3 & a2
    If a3 = 5 Then a3 = "5?號"
    ans4 = ans4 & a3
    Next

    Print #2, "(2):" & ans2
    Print #2, "(3):" & ans3
    Print #2, "(4):" & ans4

    Close
    Close
    End
    End Sub

    回覆刪除
  2. 小冰好,
    程式正確。
    這題還有兩個副點,一個是用replace來做,超快。(參照學長的程式)
    另外一個是用select來將三個if合成一個判斷式中。

    回覆刪除
  3. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, n
    Print #2, Len(n)
    Print #2, Replace(n, "3", "3+")
    Print #2, Replace(n, "4", "4*")
    Print #2, Replace(n, "5", "5?")
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  4. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Dim ans2, ans3, ans4 As String
    Input #1, x
    ans1 = Len(x)
    Print #2, "(1):" & ans1
    Print #2, "(2):" & Replace(x, 4, "4*")
    Print #2, "(3):" & Replace(x, 3, "3+")
    Print #2, "(4):" & Replace(x, 5, "5?")
    Close
    Close
    End
    End Sub

    回覆刪除
  5. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, s
    Print #2, "(1):" & Len(s)
    Print #2, "(2):" & Replace(s, "4", "4*號")
    Print #2, "(3):" & Replace(s, "3", "3+號")
    Print #2, "(4):" & Replace(s, "5", "5?號")
    Close #2
    Close #1
    End
    End Sub

    回覆刪除