1
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?

5
  • 2
    what about the white space? Commented Jun 18, 2013 at 13:18
  • 1
    Guessing that you want to remove slashes except when they separate other characters. If the solidus is a separator then leave only one, i.e. "a / b / / c" -> "a / b / c". Did you write any code yet? Commented Jun 18, 2013 at 13:21
  • @HABO You are correct. I missed that out. Updated the Question. Commented Jun 18, 2013 at 13:23
  • Yes, if you have this string: abc / / cdf / / , what should it yeild? I'm guessing abc / cdf, is that correct? Commented Jun 18, 2013 at 13:23
  • Regex. Remove any leading slashes ignoring whitespace, remove any trailing slashes ignoring whitespace, collapse any other occurrences (ignoring whitespace) to a single slash. Commented Jun 18, 2013 at 13:26

3 Answers 3

6

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't this result in a string with extra white space in it? Might need to .Trim() the strings in the array before you can join them.
2
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.

1 Comment

This functioned for the original examples 1 - 4, but not for the newly added example 5.
1

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 ($)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.