Question

I'm reviewing some existing code (converted from C#). It currently includes this expression:

Value.Substring(Value.IndexOf(symbol), 1)

where symbol is a Char from Value, a String. (Yes, it is from For Each symbol As Char In Value.)

As far as I can tell from MSDN this will be identical to:

symbol.ToString

(which will be much faster).

Can anyone suggest any situation when this won't be the case?

Note I do see the "flaw" in this code that means it may refer to an earlier version of symbol in Value than the one we're really considering, but that is part of my question: can this ever actually matter?

(Obviously another solution is to rework the code to For i = 0 To Value.Length - 1: symbol = Value(i): ... Value.Substring(i, 1) ... to keep the reference to the original string, just in case.)

    ''' <summary>
    ''' This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
    ''' While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
    ''' </summary>
    ''' <param name="Value">The value to Url encode</param>
    ''' <returns>Returns a Url encoded string</returns>
    Public Function UrlEncode(ByVal Value As String) As String
        Dim result As New StringBuilder()

        For Each symbol As Char In Value
            If unreservedChars.IndexOf(symbol) <> -1 Then
                result.Append(symbol)
            Else
                'some symbols produce > 2 char values so the system urlencoder must be used to get the correct data
                Dim hexAscW As String = String.Format("{0:X2}", CInt(AscW(symbol)))
                If hexAscW.Length > 3 Then
                    result.Append(HttpUtility.UrlEncode(Value.Substring(Value.IndexOf(symbol), 1)).ToUpper())
                Else
                    result.Append("%"c & hexAscW)
                End If
            End If
        Next
        Return result.ToString()
    End Function

I've already refactored the hexAscW which was originally a duplicated expression.

Était-ce utile?

La solution

You have 2 ?
Answering the question in the title.
Does String.IndexOf(Char) always point to the same character Char?
From the documentation yes.

String.IndexOf Method (Char)

Reports the zero-based index of the first occurrence of the specified Unicode character in this string.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top