Last but one Char in vb.net String
How do I find last but one cha开发者_高级运维racter in a vbstring
for e.g. In the string V1245-12V0 I want to return V
Don't use substring to get just one character
Dim MyString As String = "V1245-12V0"
Dim MyChar As Char = MyString(MyString.Length - 2)
Sorry it's been a while since I did VB so this may not be perfect (and is probably a mixture of C# and VB) but you get the idea:
Dim s = "V1245-12V0"
Dim lastButOneLetter = String.Empty
If s.Length > 1 Then
'Can only get the last-but-one letter from a string that is minimum 2 characters
lastButOneLetter = s.Substring(s.Length - 2, 1)
Else
'do something if string is less than 2 characters
End If
EDIT: fixed to be compilable VB.NET code.
Dim secondToLastChar As Char
secondToLastChar = Microsoft.VisualBasic.Strings.GetChar(mystring, mystring.Length - 2)
http://msdn.microsoft.com/en-us/library/4dhfexk4(VS.80).aspx
Or just remember that any string is an array of chars;
secondToLastChar = mystring(mystring.Length - 2)
If you want to get the last alpha-character in a string you could use a LINQ query such as (C#):
var d = from c in myString.ToCharArray().Reverse()
where Char.IsLetter(c)
select c;
return d.First();
string.Substring(string.Length - 2, 1);
Was it difficult?
dim mychar as string
dim yourstring as string
yourstring="V1245-12V0"
mychar=yourstring.Substring(yourstring.Length - 2, 1)
Use the Substring
on the string s which contains 'V1245-12V0'
s.Substring(s.Length - 2, 1);
Here's a VB solution:
Dim text = "V1245-12V0"
Dim v = Left(Right(text, 2), 1)
You do not need to check the length of text
, except for your semantics as to what you want to happen for empty (and Nothing
) and single character strings.
You can have your own functions like
Function Left(ByVal str as string, byval index as integer) As String
Left=str.Substring(0,index);
End Function
Function Right(ByVal str as string, byval index as integer) As String
Right=str.Substring(str.Length-index)
End Function
And use them to get what you need.
精彩评论