我如何创建一个接受字符串并用空字符串替换所有不可打印字符(< 32或> 126)的vb.net函数?
答案 0 :(得分:2)
您可以逐字逐句地查看字符串:
Private Function Convert(input As String) As String
Dim asArray As Char() = input.ToCharArray()
For i As Integer = 0 To asArray.Length - 1
If AscW(asArray(i)) < 32 OrElse AscW(asArray(i)) > 126 Then
asArray(i) = " "C
End If
Next
Return New String(asArray)
End Function
答案 1 :(得分:1)
试试这个。它使用一组合法字符,目前所有的Ascii值都是32-126。
Private Function convertChars(input As String) As String
Const legalchars As String = " !""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
Dim rv As New System.Text.StringBuilder
For Each c As Char In input
If legalchars.IndexOf(c) > 0 Then rv.Append(c)
Next
Return rv.ToString
End Function
答案 2 :(得分:0)
您也可以使用LINQ:
Dim startstring As String = "ferojifsdajknf" + Chr(0) + "sdiojufsda" + Chr(20) + "jikwfe"
Dim result As String = Join((From c As Char In startstring
Where Asc(c) >= 32 AndAlso Asc(c) <= 126
Let s = c.ToString
Select s).ToArray, "")
?startstring.ToCharArray
{Length=32}
(0): "f"c
(1): "e"c
(2): "r"c
(3): "o"c
(4): "j"c
(5): "i"c
(6): "f"c
(7): "s"c
(8): "d"c
(9): "a"c
(10): "j"c
(11): "k"c
(12): "n"c
(13): "f"c
(14): "
(15): "s"c
(16): "d"c
(17): "i"c
(18): "o"c
(19): "j"c
(20): "u"c
(21): "f"c
(22): "s"c
(23): "d"c
(24): "a"c
(25): ""c
(26): "j"c
(27): "i"c
(28): "k"c
(29): "w"c
(30): "f"c
(31): "e"c
?result.ToCharArray
{Length=30}
(0): "f"c
(1): "e"c
(2): "r"c
(3): "o"c
(4): "j"c
(5): "i"c
(6): "f"c
(7): "s"c
(8): "d"c
(9): "a"c
(10): "j"c
(11): "k"c
(12): "n"c
(13): "f"c
(14): "s"c
(15): "d"c
(16): "i"c
(17): "o"c
(18): "j"c
(19): "u"c
(20): "f"c
(21): "s"c
(22): "d"c
(23): "a"c
(24): "j"c
(25): "i"c
(26): "k"c
(27): "w"c
(28): "f"c
(29): "e"c