Anuya
Anuya

Reputation: 8350

How to remove a char in string using vb.net?

string Example 1 : abc / 
string Example 2 : abc / cdf / / 
string Example 3 : abc / / / /
string Example 4 : / / / / / 
string Example 5 : abc / / xyz / / /  

I need to remove the slashes in string with many scenarios. I guess the scenarios is self explanatory in the expected result below.

Result:

    string Example 1 : abc 
    string Example 2 : abc / cdf 
    string Example 3 : abc  
    string Example 4 :  
    string Example 5 : abc / xyz 

How do I do this usng vb.net?

Upvotes: 1

Views: 412

Answers (3)

SysDragon
SysDragon

Reputation: 9888

Try this:

Dim s As String '= ...
Dim aux() As String

aux = s.Split(New Char() {"/"c}, StringSplitOptions.RemoveEmptyEntries)
s = String.Join("/", aux)

You may want to handle the white spaces:

aux = s.Split("/ ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
s = String.Join(" / ", aux)

Upvotes: 6

Piotr Stapp
Piotr Stapp

Reputation: 19830

You could use Rexexp expression. Bellow should work:

 "(/\s+)+$"

it search for:

  1. '/'
  2. followed by one or more white-chars: \s+
  3. multiple times - expression: (/\s+)+
  4. in the end of string ($)

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 415820

Function RemoveTrailingSlash(ByVal s as String) As String
    'Note that space is included in this array
    Dim slash() As Char = "/ ".ToCharArray()
    s = s.TrimEnd()
    While s.EndsWith("/")
        s = s.TrimEnd(slash)
    End While
    Return s
End Function

Typed directly into the reply window (not tested!), but I think it will work.

Upvotes: 2

Related Questions