Get the first character of string using VB.NET
18,062
Solution 1
The easiest is using LINQ:
Dim firstChar = str.First()
Dim lastChar = str.Last()
You can use LINQ since a String
is also an IEnumerable(Of Char)
implicitely.
You can also use it like a Char-Array
(String.Chars
is the default property) and access the first and last char via index:
firstChar = str(0)
lastChar = str(str.Length - 1)
Solution 2
Dim test As String = "test!"
Dim first As String = test.Substring(0, 1)
Dim last As String = StrReverse(test).Substring(0, 1)
MessageBox.Show("First: " & first & " Last:" & last)
Author by
BlackOpty
Updated on July 14, 2022Comments
-
BlackOpty almost 2 years
Let’s say that my string is:
test!
I want to get the first character
t est!
Also I want to get the last character
test
!
How can I do that?
-
asawyer almost 12 yearsAddressing your edit, I'd say the opposite is true. The linq statements clearly expresses the intent of the code, while this example is more muddled in the implementation.
-
Olly almost 12 yearsFrankly, I would often just use Linq too. The arguments against? It's (as I understand it) significantly higher overhead. Often this may be irrelevant, but there is a case for saying it's better to be in the habit of writing more efficient code, especially when there's not much else to choose between them. Linq also forces a dependency on .Net 3.5; the character index method has existed since v1.0. But, in the end, it's horses for courses!
-
Olly almost 12 yearsA straightforward suggestion, but if performance is at all relevant, just consider what work is being done internally to get the last character: the entire string must be reversed character-by-character simply to get a single character back. It's an easy to read, concise solution though if performance is not an issue.
-
talha2k almost 12 yearsYeah Linq option is a better way. But this is a simple and straight solution. :)