Feeling dumb, I'm trying to remove a sub string after the la开发者_JAVA百科st occurrence of a ".". The code is as follows:
Dim dotIndex As Integer = fileNameCopy.LastIndexOf(".")
Dim dummy As Integer = fileNameCopy.Length - 1
fileNameCopy = fileNameCopy.Remove(dotIndex, dummy)
When I debug, I get an argument out of range exception for the second, counter, parameter; dummy in this case. I'm not sure why; the total length of my test string is 72, when debugging, the dotIndex is 68 and the length is 71, so I'm within the bounds of the string, I'm not sure why I'm getting this error, any help is appreciated.
The second parameter is not the last index of the substring your want to remove but rather the number of characters to be removed after your starting index.
This should work:
Dim myString as String = "abc.efg"
Dim dotIndex As Integer = myString.LastIndexOf(".")
Dim dummy As Integer = myString.Length - dotIndex
myString = myString.Remove(dotIndex, dummy)
You can also just do
Dim myString as String = "abc.efg"
Dim dotIndex As Integer = myString.LastIndexOf(".")
myString = myString.Remove(dotIndex)
which will remove all characters after the one at dotIndex position.
Or you can go an even simpler way. Judging by your variable names, you're just trying to remove the extension from a filename. Try this:
fileNameCopy = Path.GetFileNameWithoutExtension(fileNameCopy)
Like I said, I'm feeling dumb. Misinterpreted the second parameter, some simple arithmetic and presto.
Dim dotIndex As Integer = fileNameCopy.LastIndexOf(".")
Dim charCount As Integer = fileNameCopy.Length - dotIndex
fileNameCopy = fileNameCopy.Remove(dotIndex, charCount)
精彩评论