Reputation: 5162
having a few issues trying to convert this code snippet to C#
Private Shared Function GetOccInt(ByVal itm As String) As Integer
Dim pos As Integer = InStr(itm, ">")
Dim strTemp As String = Trim(Replace(Right(Trim(itm), itm.Length - pos), "</b>)</a>", String.Empty))
pos = InStr(strTemp, ">")
Return Convert.ToInt32(Trim(Right(strTemp, strTemp.Length - pos)))
End Function
My final attempt which should be right is, but clearly isn't:
private static int GetOccInt(string itm)
{
var pos = itm.IndexOf(">", StringComparison.Ordinal);
var strTemp = itm.Trim().Substring(itm.Length - pos, itm.Length).Replace("</b>)</a>", "");
pos = strTemp.IndexOf(">", StringComparison.Ordinal);
return Convert.ToInt32(strTemp.Trim().Substring(strTemp.Length - pos, strTemp.Length));
}
when debugging, I'm getting an argument out of range error for the substring function, message = Index and length must refer to a location within the string. Parameter name: length
The first time the breakpoint hit, the index was right (12) and the itm.Length said 31 and it appeared to have 31 charachters, but since itm.length is system code not sure how that could generate an error.
Upvotes: 1
Views: 3586
Reputation: 172230
Why reinvent the wheel? You can add a reference to the Microsoft.VisualBasic library and just use Strings.Right.
If you don't want to add that reference, the canonical replacement for Right(str, i)
is str.Substring(str.Length - i)
(only one argument, you use two in your example).
Note, though, that Right
supports a target length exceeding the length of the string, whereas the replacement does not: Right("abc", 5)
will yield abc
in VB, but using "abc".Substring(3 - 5)
will yield an exception.
Upvotes: 3
Reputation: 205589
VB
Right(Trim(itm), itm.Length - pos)
corresponds to C#
itm.Trim().Substring(pos)
Upvotes: 3