String Manipulation with no delimiter - vb.net

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

Related

Get a specific value from the line in brackets (Visual Studio 2019)

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

Replacing character in a text file with comma delimited

I have a comma delimited file with sample values :
1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT
Question : how to replace the comma in the last column which is "AAA,TEXT"
The result should be this way:
1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
There is an overload of String.Split which takes an argument telling it the maximum number of parts to return. You could use it like this:
Option Infer On
Option Strict On
Module Module1
'TODO: think up a good name for this function
Function X(s As String) As String
Dim nReturnParts = 7
Dim parts = s.Split({","c}, nReturnParts)
If parts.Count < nReturnParts Then
Throw New ArgumentException($"Not enough parts - needs {nReturnParts}.")
End If
parts(nReturnParts - 1) = parts(nReturnParts - 1).Replace(",", "")
Return String.Join(",", parts)
End Function
Sub Main()
Dim s() = {"1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT",
"1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT",
"1,1076103,22-NOV-16,21051169,50,1083,C,C,C,TEXT"}
For Each a In s
Console.WriteLine(X(a))
Next
Console.ReadLine()
End Sub
End Module
Outputs:
1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT
1,1076103,22-NOV-16,21051169,50,1083,CCCTEXT
Is simple, but learn a bit how to use string ;)
Public Function MDP(strWork As String)
Dim splitted() As String = strWork.Split(","c)
Dim firsts As New List(Of String)
For i As Integer = 0 To splitted.Count - 3
firsts.Add(splitted(i))
Next
Dim result As String = System.String.Join(",", firsts)
Return result & "," & splitted(splitted.Count - 2) & splitted(splitted.Count - 1)
End Function
Then call with:
Dim finished As String = MDP("1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT")

I want to have extra characters that will serve as divider my to string

Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
For Each word In list
MsgBox(list)
Next
Catch ex As Exception
End Try
End Sub
The value of paramater "value" is this :
7/28/2016 10:19:27 AM#-!-#Alex17282016#-!-#Outgoing#-!-#Alex#-!-#Alex#-!-#Text#-!-#1ST
Then I split the values and change the word Outgoing to Incoming.
Now I want my string to to look like this again
7/28/2016 10:19:27 AM#-!-#Alex17282016#-!-#Incoming#-!-#Alex#-!-#Alex#-!-#Text#-!-#1ST
Sorry for my grammar. I hope you understand my question
Below I have edited your code you already have to make the string the way you want it after changing "Outgoing" to "Incoming":
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Dim newValue as String = ""
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
For Each word In list
newValue = newValue & word
Next
value = newValue
Catch ex As Exception
End Try
End Sub
Or as Mark in the comments stated you could use string.join instead of a loop:
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
Dim newValue As String = String.Join("#-!-#", list)
Catch ex As Exception
End Try
End Sub
Below is code I think would work better, as it does it one line of code and doesn't need to split the string apart and put it back together:
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
value = value.replace("#-!-#Outgoing#-!-#", "#-!-#Incoming#-!-#")
End Sub

how to select the strings between the textbox.contain() code?

What I want to do actually is I want to find a strings in a textbox. My idea is using IF to find the current string for example;
If Textbox1.Contain("<") AndAlso Textbox1.Contain(">") Then
'I want to select the strings between the < and > to do MySQL command.
End If
How can I do that? Thank you guys for your help!
A solution without messing with RegEx could be this (it really depends on your needs):
<HideModuleName>
Public Module StringExtensions
<Extension>
Public Function GetFirstStringBetween(ByVal sender As String,
ByVal delimiterA As String,
ByVal delimiterB As String) As String
If sender.Contains(delimiterA) AndAlso sender.Contains(delimiterB) Then
Dim rightPart As String = sender.Substring(sender.IndexOf(delimiterA) + 1)
If rightPart.Contains(delimiterB) Then
Return rightPart.Substring(0, sender.IndexOf(delimiterB) - 1)
End If
End If
Return sender
End Function
End Module
Usage:
Dim str As String = "<Hello World> <Bye World>"
Dim result As String = str.GetFirstStringBetween("<", ">")
Console.WriteLine(result)
I'm not familiar with VB. But may be you want to try using regular expression. It's pretty useful for searching and extracting.
Something like below should work.
Dim strBetween As String
strBetween = Regex.Match(TextBox1.text, "<(.*?)>").Value
Or you can do as below example:
Sub Main()
Dim regex As Regex = New Regex("<(.*?)>")
Dim match As Match = regex.Match(TextBox1.text)
If match.Success Then
Console.WriteLine(match.Value)
End If
End Sub
Please let me know if it work.

How to get ASCII values of a string in VB.net

I want to be able so get the ASCII values of all the characters in a string.
I can get the ASCII value of a character but i cannot do it for the whole string.
My attempt:
dim input as string = console.readline()
dim value as integer = ASC(input)
'Then I am changing its value by +1 to write the input in a secret code form.
console.writeline(CHR(value+1))
I want to be able to get the ASCII values for all characters in the string so i can change the all letters in the string +1 character in the alphabet.
Any help appreciated, thanks.
Use Encoding.ASCII.GetBytes:
Dim asciis As Byte() = System.Text.Encoding.ASCII.GetBytes(input)
If you want to increase each letter's ascii value you can use this code:
For i As Int32 = 0 To asciis.Length - 1
asciis(i) = CByte(asciis(i) + 1)
Next
Dim result As String = System.Text.Encoding.ASCII.GetString(asciis)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim a As Integer
a = Asc(TextBox1.Text)
MessageBox.Show(a)
End Sub
End Class
I know it's been almost three years now, but let me show you this.
Function to convert String to Ascii (You already have a String in your Code). You can use either (Asc) or (Ascw) ... for more information, please read Microsoft Docs
Dim Input As String = console.readline()
Dim Value As New List(Of Integer)
For Each N As Char In Input
Value.Add(Asc(N) & " ")
Next
Dim OutPutsAscii As String = String.Join(" ", Value)
Function to Convert Ascii to String (What you asked for). You can use either (Chr) or (ChrW) ... for more information, please read Microsoft Docs
Dim Value1 As New List(Of Integer)
Dim MyString As String = String.Empty
For Each Val1 As Integer In Value1
MyString &= ChrW(Val1)
Next