简体   繁体   中英

remove special character from string in vb.net

this would be my string

Panipat,Patna,

Result should be Panipat,Patna

,Panipat,Patna,

Result should be Panipat,Patna

Panipat,

Result should be Panipat

,Panipat,,

Result should be Panipat

How can i do it . Need help !!

It looks like you want the Trim function

Dim result = input.Trim(New Char() { ","c })

This function will remove all occurrences of the specified characters from the start and end of the string value

Example usage

Dim str As String = "hello,"
Dim res = str.Trim(New Char() {","c})
Console.WriteLine(res) 'Prints: hello

You can get more info from here

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
   Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Try with this:

Private Sub Main()
    Dim inputText As String = "This is string ending with comma character,"

    Dim result As String = inputText.Trim(",".ToCharArray())

    Console.WriteLine(result)

End Sub

Best way to achieve your goal is use regular expression. Below example will work for two terms at a time.

eg replace ,Panipat,Patna,, with Panipat,Patna

Public Function Return_Strip_Word(Text As String) As String
    Dim reg As String = "(?<stripword>(\w+)\b,\b(\w+))"
    Dim VDMatch As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(Text, reg)
    If VDMatch.Success Then
         Return VDMatch.Groups("stripword").Value
    Else
        Return Text
    End If
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM