patternMinor
Extract a character at particular place in a string
Viewed 0 times
placecharacterextractparticularstring
Problem
I have a function:
For extracting a character at a particular place in a string, how can I shorten this or any alternate for the same purpose?
Private Function getbyte(s As String, ByVal place As Integer) As String
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End FunctionFor extracting a character at a particular place in a string, how can I shorten this or any alternate for the same purpose?
Solution
According to MSDN, this function is already implemented:
A review of your code
-
"Compress":
The first version is definitely not wrong or ugly, but why use an extra line if we could express the same logic in the same clear manner?
-
You could use
' Code from MSDN
'
Dim myString As String = "ABCDE"
Dim myChar As Char
' The value of myChar is "D".
myChar = myString.Chars(3)A review of your code
- Please indent your code.
- I would choose another, more meaningful name for your function:
getCharAtorgetByteFromString. It is now clear that the function operates on a string.
- I would use the clearer parameter name
strinstead ofs.
-
"Compress":
place = place + 1
getbyte = Mid(s, place, 1)
' change to
getbyte = Mid(s, place + 1, 1)The first version is definitely not wrong or ugly, but why use an extra line if we could express the same logic in the same clear manner?
-
You could use
If to shorten your code:Private Function getbyte(str As String, ByVal place As Integer) As String
getbyte = If(place < Len(str), Mid(str, place + 1, 1), "")
End FunctionCode Snippets
' Code from MSDN
'
Dim myString As String = "ABCDE"
Dim myChar As Char
' The value of myChar is "D".
myChar = myString.Chars(3)place = place + 1
getbyte = Mid(s, place, 1)
' change to
getbyte = Mid(s, place + 1, 1)Private Function getbyte(str As String, ByVal place As Integer) As String
getbyte = If(place < Len(str), Mid(str, place + 1, 1), "")
End FunctionContext
StackExchange Code Review Q#58895, answer score: 6
Revisions (0)
No revisions yet.