I tried to create a unique code for each shop in the form I made. I have two TextBox controls (TBNameStore and TBCodeStore). What I want is that when I write the name of the shop, for example "Brothers in Arm", in TBNameStore, then TBCodeStore should automatically be filled with the text "BIA".
How can I do that?
Well I write a code that can help you with your problem.
Option Strict On
Public Class Form1
Public Function GetInitials(ByVal MyText As String) As String
Dim Initials As String = ""
Dim AllWords() As String = MyText.Split(" "c)
For Each Word As String In AllWords
If Word.Length > 0 Then
Initials = Initials & Word.Chars(0).ToString.ToUpper
End If
Next
Return Initials
End Function
Private Sub TBNameStore_TextChanged(sender As Object, e As EventArgs) Handles TBNameStore.TextChanged
TBCodeStore.Text = GetInitials(TBNameStore.Text)
End Sub
End Class
Like you can see, the GetInitials get you all the first letter of all the words in the text.
One possible solution using the mentioned Split and SubString methods and LINQ could look like this:
create a StringBuilder where every first character of each word is stored
separate the words using the specified delimiter (default is empty space) using the String.Split method
convert the array to list in order to apply the LINQ-ToList extension => ToList()
for each found word => ForEach(sub (word as String) ...
take the first character from the word, convert it to upper case and put it in the result
=> result.Append(word.SubString(0, 1).ToUpper())
return the result as string => result.ToString()
The code looks like this:
private function abbreviation(input as String, optional delimiter as String = " ")
dim result = new StringBuilder()
input.Split(delimiter) _
.ToList() _
.ForEach(sub (word as String)
result.Append(word.SubString(0, 1).ToUpper())
end sub)
return result.ToString()
end function
Usage:
dim s = "Brothers in Arms"
Console.WriteLine("{0} => {1}", s, abbreviation(s))
and the output looks like expected:
Brothers in Arms => BIA
Related
I would like to ask for your help regarding my problem. I want to create a module for my program where it would read .txt file, find a specific value and insert it to the text box.
As an example I have a text file called system.txt which contains single line text. The text is something like this:
[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]
What i want to do is to get only the last name value "xxx_xxx" which every time can be different and insert it to my form's text box
Im totally new in programming, was looking for the other examples but couldnt find anything what would fit exactly to my situation.
Here is what i could write so far but i dont have any idea if there is any logic in my code:
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(C:\test\test_1\db\update\network\system.txt)
For i = 1 To 3
If line.Contains("Last Name=" & i) Then
field.Add(line.Substring(line.IndexOf("=") + 2))
End If
Next
Next
End Sub
Im
You can get this down to a function with a single line of code:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Return File.ReadLines(fileName).Where(Function(line) RegEx.IsMatch(line, "[[[]Last Name=(?<LastName>[^]]+)]").Select(Function(line) RegEx.Match(line, exp).Groups("LastName").Value)
End Function
But for readability/maintainability and to avoid repeating the expression evaluation on each line I'd spread it out a bit:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Dim exp As New RegEx("[[[]Last Name=(?<LastName>[^]]+)]")
Return File.ReadLines(fileName).
Select(Function(line) exp.Match(line)).
Where(Function(m) m.Success).
Select(Function(m) m.Groups("LastName").Value)
End Function
See a simple example of the expression here:
https://dotnetfiddle.net/gJf3su
Dim strval As String = " [Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim strline() As String = strval.Split(New String() {"[", "]"}, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(s) Not String.IsNullOrWhiteSpace(s)) _
.ToArray()
Dim lastnameArray() = strline(1).Split("=")
Dim lastname = lastnameArray(1).ToString()
Using your sample data...
I read the file and trim off the first and last bracket symbol. The small c following the the 2 strings tell the compiler that this is a Char. The braces enclosed an array of Char which is what the Trim method expects.
Next we split the file text into an array of strings with the .Split method. We need to use the overload that accepts a String. Although the docs show Split(String, StringSplitOptions), I could only get it to work with a string array with a single element. Split(String(), StringSplitOptions)
Then I looped through the string array called splits, checking for and element that starts with "Last Name=". As soon as we find it we return a substring that starts at position 10 (starts at zero).
If no match is found, an empty string is returned.
Private Function readcrnFile() As String
Dim LineInput = File.ReadAllText("system.txt").Trim({"["c, "]"c})
Dim splits = LineInput.Split({"]["}, StringSplitOptions.None)
For Each s In splits
If s.StartsWith("Last Name=") Then
Return s.Substring(10)
End If
Next
Return ""
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = readcrnFile()
End Sub
You can easily split that line in an array of strings using as separators the [ and ] brackets and removing any empty string from the result.
Dim input As String = "[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim parts = input.Split(New Char() {"["c, "]"c}, StringSplitOptions.RemoveEmptyEntries)
At this point you have an array of strings and you can loop over it to find the entry that starts with the last name key, when you find it you can split at the = character and get the second element of the array
For Each p As String In parts
If p.StartsWith("Last Name") Then
Dim data = p.Split("="c)
field.Add(data(1))
Exit For
End If
Next
Of course, if you are sure that the second entry in each line is the Last Name entry then you can remove the loop and go directly for the entry
Dim data = parts(1).Split("="c)
A more sophisticated way to remove the for each loop with a single line is using some of the IEnumerable extensions available in the Linq namespace.
So, for example, the loop above could be replaced with
field.Add((parts.FirstOrDefault(Function(x) x.StartsWith("Last Name"))).Split("="c)(1))
As you can see, it is a lot more obscure and probably not a good way to do it anyway because there is no check on the eventuality that if the Last Name key is missing in the input string
You should first know the difference between ReadAllLines() and ReadLines().
Then, here's an example using only two simple string manipulation functions, String.IndexOf() and String.Substring():
Sub Main(args As String())
Dim entryMarker As String = "[Last Name="
Dim closingMarker As String = "]"
Dim FileName As String = "C:\test\test_1\db\update\network\system.txt"
Dim value As String = readcrnFile(entryMarker, closingMarker, FileName)
If Not IsNothing(value) Then
Console.WriteLine("value = " & value)
Else
Console.WriteLine("Entry not found")
End If
Console.Write("Press Enter to Quit...")
Console.ReadKey()
End Sub
Private Function readcrnFile(ByVal entry As String, ByVal closingMarker As String, ByVal fileName As String) As String
Dim entryIndex As Integer
Dim closingIndex As Integer
For Each line In File.ReadLines(fileName)
entryIndex = line.IndexOf(entry) ' see if the marker is in our line
If entryIndex <> -1 Then
closingIndex = line.IndexOf(closingMarker, entryIndex + entry.Length) ' find first "]" AFTER our entry marker
If closingIndex <> -1 Then
' calculate the starting position and length of the value after the entry marker
Dim startAt As Integer = entryIndex + entry.Length
Dim length As Integer = closingIndex - startAt
Return line.Substring(startAt, length)
End If
End If
Next
Return Nothing
End Function
Using VB I am trying to create a name for the file by concatenating together the words "NewEmployeesOut" with the short date and time of the day. I am getting the following error System.NotSupportedException: 'The given path's format is not supported.' Below is the Code I am currently using, it seems like VB does not like a character I am using in my concat function when trying to export the .txt file.
Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
Dim writeRecord As New StreamWriter
(New FileStream("NewEmployeesOut" & Date.Today.ToShortDateString & Date.Now.ToShortTimeString & ".txt", FileMode.Append, FileAccess.Write))
Dim EmployeeInformation1 As New EmployeeInformation()
writeRecord.Write(EmployeeInformation1.LastName & "|")
writeRecord.Write(EmployeeInformation1.FirstName & "|")
writeRecord.Write(EmployeeInformation1.DepartmentNo & "|")
writeRecord.Write(EmployeeInformation1.CreateUserName(EmployeeInformation1.FirstName, EmployeeInformation1.LastName) & "|")
writeRecord.WriteLine(EmployeeInformation1.CreatePassword)
writeRecord.Close()
End Sub
From MS docs https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
The following characters are resevered.
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
A file name formatted as follows will pass muster. The uppercase HH gives you 24 hour time.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fileName As String = "NewEmployeesOut" & Now.ToString(" MMMM dd, yyyy HH,mm") & ".txt"
Debug.Print(fileName)
File.CreateText(fileName)
End Sub
In the immediate window...
NewEmployeesOut December 10, 2020 18,07.txt
Your short date probably looks like "31/12/2020" or "12/31/2020" which are no valid file names. Try something like
Dim now As DateTime = DateTime.Now
Dim fileName As String = $"NewEmployeesOut_{now:yyyy-MM-dd}_{now:HHmm}.txt"
Concerning the other question: It's the wrong place to post it, don't ask another question within a comment.
I think you have to learn a bit the basics first, read/watch some VB.Net tutorials and maybe some clean-code principles like the clean-code-techniques. Your questions suggest that you don't know yet how to write simple code.
Try to structure what you are doing, avoid (like in your example) to copy 4 times the same lines of code but to create functions instead to encapsulate business logic. e.g. writing a file has nothing to do with assembling a file name, therefore the two things should not be conducted in the same method etc.
But this all said, here an idea how you could structure your code (from the comment not the main question), although I'm not too positive about the usability of the two random digits...
Usage:
Dim fileName As String = GetFileName("Smith", "John")
Methods/Properties:
Private Shared Function GetFileName(lastName As String, firstName As String) As String
lastName = NormalizeAndCrop(lastName, 7)
firstName = NormalizeAndCrop(firstName, 10)
Dim randomNumber As Int32 = Randomizer.Next(0, 100)
Return $"{lastName}{firstName}{randomNumber:00}"
End Function
Private Shared Function NormalizeAndCrop(text As String, length As Int32)
'Check args
If (length < 0) Then Throw New ArgumentOutOfRangeException(NameOf(length), length, "A non-negative value expected!")
If (text Is Nothing) OrElse (length = 0) Then Return String.Empty
text = text.Normalize()
'Copy only valid characters
Dim result As New StringBuilder()
For i As Int32 = 0 To text.Length - 1
Dim c As Char = text(i)
If (IsValidFileNameChar(c)) Then
result.Append(c)
If (result.Length = length) Then
Return result.ToString()
End If
End If
Next
Return result.ToString()
End Function
Private Shared Function IsValidFileNameChar(c As Char) As Boolean
If (Char.IsControl(c)) Then Return False
If (InvalidFileNameChars.IndexOf(c) > -1) Then Return False
Return True
End Function
Private Shared ReadOnly Property Randomizer As Random = New Random(Environment.TickCount)
Private Shared ReadOnly Property InvalidFileNameChars As String = New String(Path.GetInvalidFileNameChars())
I'm beginner with VB.net.
How do I read indexes for certain character in a string? I read an barcode and I get string like this one:
3XXX123456-C-AA123456TY-667
From that code I should read indexes for character "-" so I can cut the string in parts later in the code.
For example code above:
3456-C
6TY-667
The length of the string can change (+/- 3 characters). Also the places and count of the hyphens may vary.
So, I'm looking for code which gives me count and position of the hyphens.
Thanks in advance!
Use the String.Splt method.
'a test string
Dim BCstring As String = "3XXX123456-C-AA123456TY-667"
'split the string, removing the hyphens
Dim BCflds() As String = BCstring.Split({"-"c}, StringSplitOptions.None)
'number of hyphens in the string
Dim hyphCT As Integer = BCflds.Length - 1
'look in the debuggers immediate window
Debug.WriteLine(BCstring)
'show each field
For Each s As String In BCflds
Debug.WriteLine(String.Format("{0,5} {1}", s.Length, s))
Next
'or
Debug.WriteLine(BCstring)
For idx As Integer = 0 To hyphCT
Debug.WriteLine(String.Format("{0,5} {1}", BCflds(idx).Length, BCflds(idx)))
Next
If all you need are the parts between hyphens then as suggested by dbasnett use the split method for strings. If by chance you need to know the index positions of the hyphens you can use the first example using Lambda to get the positions which in turn the count give you how many hyphens were located in the string.
When first starting out with .NET it's a good idea to explore the various classes for strings and numerics as there are so many things that some might not expect to find that makes coding easier.
Dim barCode As String = "3XXX123456-C-AA123456TY-667"
Dim items = barCode _
.Select(Function(c, i) New With {.Character = c, .Index = i}) _
.Where(Function(item) item.Character = "-"c) _
.ToList
Dim hyphenCount As Integer = items.Count
Console.WriteLine("hyphen count is {0}", hyphenCount)
Console.WriteLine("Indices")
For Each item In items
Console.WriteLine(" {0}", item.Index)
Next
Console.WriteLine()
Console.WriteLine("Using split")
Dim barCodeParts As String() = barCode.Split("-"c)
For Each code As String In barCodeParts
Console.WriteLine(code)
Next
Here is an example that'll split your string and allow you to parse through the values.
Private Sub TestSplits2Button_Click(sender As Object, e As EventArgs) Handles TestSplits2Button.Click
Try
Dim testString As String = "3XXX123456-C-AA123456TY-667"
Dim vals() As String = testString.Split(Convert.ToChar("-"))
Dim numberOfValues As Integer = vals.GetUpperBound(0)
For Each testVal As String In vals
Debug.Print(testVal)
Next
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
End Try
End Sub
I have some simply problem i guess, if you see below statments work without the last one: ValueFromTextFile which its value comming from my text file. This value in text file is exactly the same: "vbTab" - however it looks like when i trying to get it from my text file its not recognized the same as first line {vbTab} from example. Why is that?
.Delimiters = New String() {vbTab} <- this works
.Delimiters = New String() {","} <- this works
.Delimiters = New String() {ValueFromTextFile} <- this doesn't work
EDIT: (helper delimeter class):
Public Class CharDelimeterHelper
Private _delimeter As String
Public Sub New(ByVal delimeter As String)
Me._delimeter = delimeter
End Sub
Function GetDelimeterFormat() As ??
Dim result As ??
Select Case _delimeter
Case "vbTab"
result = ControlChars.Tab
Case ","
result = ","
Case Else
End Select
Return result
End Function
End Class
The string "vbTab" is not the same as the constant vbTab.
So if ValueFromTextFile equals "vbTab" is only works if all fields are separated by the string "vbTab" which i strongly doubt. I guess that they are separated by the tab-character which is represented by the vbTab-constant. You could also use ControlChars.Tab.
I have a string where I need to replace every character in that string with another value. That string has no delimiter. Is it possible to step through that string and replace every value with a set of predetermined values? I would like to keep it to one function as it is going to live within SSRS
Dim stringToChange As String = "123456ALWRYA"
I would then have to step through the string and replace all off the current values with new ones.
i.e. A=001, B=002, 1=101, 2=102, etc.
Is this possible if the string does not have a delimiter?
Thanks in advance!
SSRS Custom code has a pretty limited dialect, but this worked for me.
Add the following to the report Custom Code:
Function SingleReplace (SingleChar As String) As String
Select Case SingleChar
Case "A"
SingleReplace = "001"
Case "B"
SingleReplace = "002"
Case Else
SingleReplace = SingleChar
End Select
End Function
Function CustomReplace (BaseString As String) As String
Dim NewString As New System.Text.StringBuilder
For Each SingleChar As Char in BaseString
NewString.Append(SingleReplace(SingleChar))
Next
Return NewString.ToString()
End Function
Call this in a report expression with:
=Code.CustomReplace(Fields!MyString.Value)
Works for me in a simple report/table:
This is basically what Styxxy suggested...with a Dictionary for the looking up the values:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim stringToChange As String = "123456ALWRYA"
Debug.Print(stringToChange)
Dim changedString = ConvertString(stringToChange)
Debug.Print(changedString)
End Sub
Private Function ConvertString(ByVal inStr As String) As String
Static dict As New Dictionary(Of Char, String)
If dict.Count = 0 Then
dict.Add("A"c, "001")
dict.Add("B"c, "002")
dict.Add("1"c, "101")
dict.Add("2"c, "102")
' ... etc ...
End If
Dim sb As New System.Text.StringBuilder
For Each c As Char In inStr.ToUpper
If dict.ContainsKey(c) Then
sb.Append(dict(c))
Else
' ... possibly throw an exception? ...
sb.Append(c)
End If
Next
Return sb.ToString
End Function