We introduce TrimPunctuation. This counts punctuation characters at the start and the end. We use 2 for-loops and call Char.IsPunctuation to check each character.
Module Module1
Sub Main()
Dim values() As String = {
"One?",
"--two--",
"...three!",
"four",
"",
"five*"}
' Loop over strings and call TrimPunctuation.
For Each value As String In values
Console.WriteLine(TrimPunctuation(value))
Next
End Sub
Function TrimPunctuation(ByVal value As String)
' Count leading punctuation.
Dim removeFromStart As Integer = 0
For i As Integer = 0 To value.Length - 1 Step 1
If Char.IsPunctuation(value(i)) Then
removeFromStart += 1
Else
Exit For
End If
Next
' Count trailing punctuation.
Dim removeFromEnd As Integer = 0
For i As Integer = value.Length - 1 To 0 Step -1
If Char.IsPunctuation(value(i)) Then
removeFromEnd += 1
Else
Exit For
End If
Next
' Remove leading and trailing punctuation.
Return value.Substring(removeFromStart,
value.Length - removeFromEnd - removeFromStart)
End Function
End Module
One
two
three
four
five