Kat
Kat

Reputation: 2500

VB.Net concatenating strings, adding strange spaces

I'm sending a function a structure property that's a string (that's been already processed). It's an IP addr. Specifically:

 Dim ipaddr As String = "192.168.2.112"

At least, this is the value that we get after I do some processing. It looks like this in my local variable window mid build, so I know that it's looking ok. I'm trying to make a request string for the HTTP command. So I concatenate like so:

 Dim ReqStr As String = "http://" & ipaddr & "/cgi-bin/cmd/"

BUT doing so makes these strange spaces! As in the resulting string is

"http://192.168.2.112   /cgi-bin/cmd"

I thought the resulting code was maybe getting non ASCII character values, so I put it though a "\S+" regular expression, or I did ipaddr.trimend() or .trim, etc. ALL of these add the spaces. When I look at ipaddr in the locals when building, it ends at the proper end of the ipaddr value.

Yet, when I just put a hard coded string ("192.168.2.112") into the ipaddr's place in the string concatenation, no spaces. How do I get rid of the "secret" ascii characters I can't see?

Edit

Here is a sample of code which reproduces the problem:

Dim bytes() As Byte = {49, 57, 50, 46, 49, 54, 56, 46, 50, 46, 49, 49, 50, 0, 0, 0}
Dim ipaddr As String = Encoding.ASCII.GetString(bytes)
Dim ReqStr As String = "http://" & ipaddr.TrimEnd() & "/cgi-bin/cmd/"

Upvotes: 3

Views: 1680

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27322

The byte array that you posted shows that you have NUL characters in your string so the standard Trim won't work as this only removes spaces.

Try using the overloaded Trim which accepts characters to Remove the null characters:

Dim ReqStr As String = "http://" & ipaddr.Trim(Convert.ToChar(0)) & "/cgi-bin/cmd/"

A better solution might be to use the IPAddress Type (from the System.Net namespace) to hold your IP address. This won't solve your problem but it will throw a runtime error converting your rogue array into an address:

Dim ip As IPAddress = Nothing
If Not IPAddress.TryParse(Encoding.ASCII.GetString(bytes), ip) Then
    'ip address is not valid
End If
Dim ReqStr As String = "http://" & ip.ToString & "/cgi-bin/cmd/"

Upvotes: 2

Related Questions