Replace a text with all alphabet VB.NET - vb.net

I just stopped by this error
System.NullReferenceException was unhandled HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=System.Windows.Forms StackTrace:
at System.Windows.Forms.RichTextBox.StreamIn(String str, Int32 flags)
at System.Windows.Forms.RichTextBox.set_SelectedText(String value)
at Novania_JAV_Viewer_EncDec.Form1.Button1_Click(Object sender, EventArgs ef) in c:\users\toshiba\documents\visual studio
2010\Projects\Novania JAV Viewer EncDec\Novania JAV Viewer
EncDec\Form1.vb:line 91
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine)
at Novania_JAV_Viewer_EncDec.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart() InnerException:
and this is my whole code, I am trying to replace all alphabet in one word, and it needs to replace one by one, and one by one variable.
the error is located here ("title") word
Do Until RichTextBox1.Find("titelz") = -1
RichTextBox1.Find("titelz")
RichTextBox1.SelectedText = titel
and this is my whole form class code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RichTextBox1.LoadFile("template.rtf")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal ef As System.EventArgs) Handles Button1.Click
Dim A As String
Replace(TextBox1.Text, "A", "5TY5")
Console.WriteLine(A)
Dim B As String
Replace(A, "B", "WEE")
Console.WriteLine(B)
Dim C As String
Replace(B, "C", "23RW")
Console.WriteLine(C)
Dim D As String
Replace(C, "D", "RW4R")
Console.WriteLine(D)
Dim E As String
Replace(D, "E", "DFS")
Console.WriteLine(E)
Dim F As String
Replace(E, "F", "R5")
Console.WriteLine(F)
Dim G As String
Replace(F, "G", "QWEDQ")
Console.WriteLine(G)
Dim H As String
Replace(G, "H", "ZDCZ")
Console.WriteLine(H)
Dim I As String
Replace(H, "I", "VGHN")
Console.WriteLine(I)
Dim J As String
Replace(I, "J", "ZSC")
Console.WriteLine(J)
Dim K As String
Replace(J, "K", "ZSD")
Console.WriteLine(K)
Dim L As String
Replace(K, "L", "WER")
Console.WriteLine(L)
Dim M As String
Replace(L, "M", "GN")
Console.WriteLine(M)
Dim N As String
Replace(M, "N", "xfv")
Console.WriteLine(N)
Dim O As String
Replace(N, "O", "DAASAD")
Console.WriteLine(O)
Dim P As String
Replace(O, "P", "WET")
Console.WriteLine(P)
Dim Q As String
Replace(P, "Q", "DFCV")
Console.WriteLine(Q)
Dim R As String
Replace(Q, "R", "ADSDA")
Console.WriteLine(R)
Dim S As String
Replace(R, "S", "SGFDG")
Console.WriteLine(S)
Dim T As String
Replace(S, "T", "SFSFD")
Console.WriteLine(T)
Dim U As String
Replace(T, "U", "AWDAD")
Console.WriteLine(U)
Dim V As String
Replace(U, "V", "RERE")
Console.WriteLine(V)
Dim W As String
Replace(V, "W", "GBGDBB")
Console.WriteLine(W)
Dim X As String
Replace(W, "X", " AWDAW ")
Console.WriteLine(X)
Dim Y As String
Replace(X, "Y", "AWDEAVA")
Console.WriteLine(Y)
Dim Z As String
Replace(Y, "Z", "AWEDWADW")
Console.WriteLine(Z)
Dim titel As String = Z
Do Until RichTextBox1.Find("titelz") = -1
RichTextBox1.Find("titelz")
RichTextBox1.SelectedText = titel
Loop
RichTextBox2.Text = RichTextBox1.Text
RichTextBox1.Clear()
RichTextBox1.LoadFile("template.rtf")
End Sub
End Class

In order to do the replace, I'd try the following code...
It uses a Dictionary type variable. They are used in .NET quite a lot as some sort of associative array.
' First, create dictionary that you can loop through.
' This variable is created on form level (so only once)
' and contains all the "words" as key-value pairs.
' So you can search for key and replace with value.
Dim replaceDictionary As New Dictionary(Of String, String) From {{"A", "5TY5"}, _
{"B", "WEE"}, _
{"C", "23RW"}, _
{"D", "RW4R"}, _
{"E", "DFS"}, _
{"F", "R5"}, _
{"G", "QWEDQ"}, _
{"H", "ZDCZ"}, _
{"I", "VGHN"}, _
{"J", "ZSC"}, _
{"K", "ZSD"}, _
{"L", "WER"}, _
{"M", "GN"}, _
{"N", "xfv"}, _
{"O", "DAASAD"}, _
{"P", "WET"}, _
{"Q", "DFCV"}, _
{"R", "ADSDA"}, _
{"S", "SGFDG"}, _
{"T", "SFSFD"}, _
{"U", "AWDAD"}, _
{"V", "RERE"}, _
{"W", "GBGDBB"}, _
{"X", " AWDAW "}, _
{"Y", "AWDEAVA"}, _
{"Z", "AWEDWADW"}
}
Private Sub btnReplace_Click(sender As System.Object, e As System.EventArgs) Handles btnReplace.Click
' Declare temporary variable to store text
Dim tmpText As String = txtTitel.Text
' Loop through dictionary
For Each replaceItem In replaceDictionary
' Replace key ("A" etc.) with value ("5TY5" etc.)
' and store in temporary variable
tmpText = Replace(tmpText, replaceItem.Key, replaceItem.Value)
Next
'Display text
txtTitel.Text = tmpText
End Sub
Now for your "find" part... nothing like "titelz" is going to be changed with above code (only caps), so if it was in there, it stays in there.
So I have no idea what to do with that...
Edit
For the record: this goes for a long line of replaces... Once you've replaced all the A's in your string, the T from "5TY5" will also be replaced.
If you don't want this, you'll have to split the original text into characters and start checking them one by one.
Checking title string one letter at a time
There are a few changes to above code:
Dictionary is now of type (Char, String) instead of 2 strings.
The title is stored in a seperate variable in order to keep working with the orignal title text.
Instead of looping through the dictionary, you loop through the title text one letter at a time.
The code is documented with comments and should be pretty self-explanatory.
Good luck!
' First, create dictionary that you can loop through.
' This variable is created on form level (so only once)
' and contains all the "words" as key-value pairs.
' So you can search for key and replace with value.
Dim replaceDictionary As New Dictionary(Of Char, String) From {{"A", "5TY5"}, _
{"B", "WEE"}, _
{"C", "23RW"}, _
{"D", "RW4R"}, _
{"E", "DFS"}, _
{"F", "R5"}, _
{"G", "QWEDQ"}, _
{"H", "ZDCZ"}, _
{"I", "VGHN"}, _
{"J", "ZSC"}, _
{"K", "ZSD"}, _
{"L", "WER"}, _
{"M", "GN"}, _
{"N", "xfv"}, _
{"O", "DAASAD"}, _
{"P", "WET"}, _
{"Q", "DFCV"}, _
{"R", "ADSDA"}, _
{"S", "SGFDG"}, _
{"T", "SFSFD"}, _
{"U", "AWDAD"}, _
{"V", "RERE"}, _
{"W", "GBGDBB"}, _
{"X", " AWDAW "}, _
{"Y", "AWDEAVA"}, _
{"Z", "AWEDWADW"}
}
Private Sub btnReplace_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReplace.Click
' Declare temporary variable to store text
Dim tmpTitle As String = txtTitel.Text
Dim tmpText As String = ""
Dim tmpLetter As Char
' Loop through title string
Dim i As Integer = 0
Do While (i < tmpTitle.Length)
' Increase counter
i += 1
' Save next letter in tmpLetter
tmpLetter = Mid(tmpTitle, i, 1)
' Check for key in dictionary
If replaceDictionary.ContainsKey(tmpLetter) Then
' When found, append associated value to tmpText
tmpText &= replaceDictionary(tmpLetter)
Else
' Not found: use letter from title string
tmpText &= CStr(tmpLetter)
End If
Loop
'Display text
txtTitel.Text = tmpText
End Sub

Related

arabic text printing using raw printing in c#

I need to print arabic text using raw printing am using below code. But its printing ????? instated of text
Public Function SendStringToPrinter(szPrinterName As String, szString As String) As Boolean
If PrinterOpen Then
Dim pBytes As IntPtr
Dim dwCount As Int32
Dim dwWritten As Int32 = 0
dwCount = szString.Length
pBytes = Marshal.StringToCoTaskMemAnsi(szString)
SendStringToPrinter = WritePrinter(hPrinter, pBytes, dwCount, dwWritten)
Marshal.FreeCoTaskMem(pBytes)
Else
SendStringToPrinter = False
End If
End Function

Joining StringBuilder

I am a newbie
I have problem with string builder. I want to show to Richtextbox in vb with Richtextbox template
i.e.
Jan 674 Meet 670 Missed 4
Feb 635 Meet 631 Missed 4
etc.
with source from datagirdview with 8 columns and xxxx rows.
for ex. columns are : Registered Date, Deadline Date, Month, Meet/Not Meet,etc.
This my Code :
For Each keyvalue As KeyValuePair(Of String, Integer) In DicMonth
sb.AppendLine(String.Format("{0} : {1}", UCase(keyvalue.Key), keyvalue.Value))
Next
For Each keyvalue1 As KeyValuePair(Of String, Integer) In DicMeetTotal
sb.AppendLine(String.Format("{0}", "MEET : " & keyvalue1.Value))
Next
RichTextBox2.Text = sb.ToString
and the result is :
Jan : 674
Feb : 635
Mar : 623
Meet : 670
Meet : 631
Meet : 621
Missed : 4
Missed : 4
Missed : 2
Assuming the same order and length of dictionaries, you can use Zip to stitch the two dictionaries together:
Sub Main
Dim sb = New StringBuilder()
Dim DicMonth = New Dictionary(Of String, Integer)() From { _
{"Jan", 674}, _
{"Feb", 635} _
}
Dim DicMeetTotal = New Dictionary(Of String, Integer)() From { _
{"Jan", 670}, _
{"Feb", 631} _
}
Dim lineStrings = DicMonth.Zip(DicMeetTotal, _
Function(m, mt) String.Format("{0} {1} Meet {2} Missed {3}", _
m.Key, m.Value, mt.Value, m.Value - mt.Value))
For Each ls In lineStrings
sb.AppendLine(ls)
Next
Console.WriteLine(sb.ToString())
End Sub
Alternatively, if there is a join key (e.g. the Key value in both dictionaries is the same), you can use Linq Join them together, like so:
Dim lineStrings = DicMonth.Join(DicMeetTotal, _
Function(m) m.Key, Function(mt) mt.Key, _
Function(m, mt) String.Format("{0} {1} Meet {2} Missed {3}", _
m.Key, m.Value, mt.Value, m.Value - mt.Value))
Edit
Assuming that you wouldn't have modelled N different dictionaries each containing just a single value (this would be a modelling error along the lines of Entity Attribute Value, IMO), I'm guessing you'll want an entity to hold the data:
Class MeetTotalEntity
Public Property Meet As Integer
Public Property Missed As Integer
Public Property Cancel As Integer
Public Property Other As Integer
End Class
And then the Zip (or Join) still holds. The Value of the second dictionary contains the above entity, so just dereference the fields accordingly.
Sub Main
Dim sb = New StringBuilder()
Dim DicMonth = New Dictionary(Of String, Integer)() From { _
{"Jan", 674}, _
{"Feb", 635} _
}
Dim DicMeetTotal = New Dictionary(Of String, MeetTotalEntity)() From { _
{"Jan", New MeetTotalEntity With {.Meet = 670, .Missed = 4, .Cancel = 10, .Other = 5}}, _
{"Feb", New MeetTotalEntity With {.Meet = 631, .Missed = 10, .Cancel = 3, .Other = 2}} _
}
Dim lineStrings = DicMonth.Zip(DicMeetTotal, _
Function(m, mt) String.Format("{0} Total {1} Meet {2} Missed {3} Cancel {4} Other {5}", _
m.Key, m.Value, mt.Value.Meet, mt.Value.Missed, mt.Value.Cancel, mt.Value.Other))
For Each ls In lineStrings
sb.AppendLine(ls)
Next
Console.WriteLine(sb.ToString())
End Sub

convert Date column to string / label if NOT IsDBNull

I am trying (much too long) to convert a DateTime column to a label.Text.
Various errors:
What am I missing?
drExpDatesRow = dtAllCompanies.Select("CompanyID = " + CompanyID.ToString())
Dim ls_ExpiresDateString As String
If (Not IsDBNull(drExpDatesRow("Expdate"))) Then
Date.TryParse(drExpDatesRow("Expdate").ToString(), ls_ExpiresDateString)
'ls_ExpiresDateString = ldt_ExpiresDate.ToString("MM/dd/yyyy")
lbl_ExpireDate.Text = ls_ExpiresDateString.ToString()
Else
lbl_ExpireDate.Text = ""
End If
System.InvalidCastException was unhandled Message=Conversion from
string "Expdate" to type 'Integer' is not valid.
Source=Microsoft.VisualBasic StackTrace:
at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String
Value)
at zzz.winCompanyInfo.CompanyInfo_Load(Object sender, EventArgs e) in C:\inetpub\zzz.vb:line 638
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) InnerException:
System.FormatException
Message=Input string was not in a correct format.
Source=Microsoft.VisualBasic
StackTrace:
at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String
Value, NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String
Value)
InnerException:
UPDATE** Added DataRow logic
When using TryParse use the same data type.
Dim drExpDatesRow = (From dr As DataRow In dtAllCompanies.Rows
Where dr("CompanyId").ToString =
CompanyID.ToString).FirstOrDefault
Dim ls_ExpiresDate As Date ' Date not String
If (Not drExpDatesRow Is Nothing) Then
If Date.TryParse(drExpDatesRow("Expdate").ToString(), ls_ExpiresDate)
lbl_ExpireDate.Text = ls_ExpiresDate.ToString()
End If
Else
lbl_ExpireDate.Text = ""
End If
You had multiple issues in your code. This one should take care of things for good
drExpDatesRow = dtAllCompanies.Select("CompanyID = " + CompanyID.ToString()) ' returns array
lbl_ExpireDate.Text = ""
If drExpDatesRow.Length > 0 Then
If (Not IsDBNull(drExpDatesRow(0)("Expdate"))) Then
Dim myDate As DateTime
Dim res As Boolean = Date.TryParse(drExpDatesRow("Expdate"), myDate)
If res Then lbl_ExpireDate.Text = MyDate.ToString("<format>")
End If
End If

SAP Catching Data with RFC_CALL_TRANSACTION RFC VB

I become an errorcode 1001, an SAP Remote error?
I've googled alot but didn't find anything.
Maybe someone knows whats the Problem here.
Im using SAP 720.
System.Runtime.InteropServices.COMException (0x000003E9): SAP Remote
Function Call bei
Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet(Object o,
Type objType, String name, Object[] args, String[] paramnames,
Boolean[] CopyBack) bei
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object
Instance, Type Type, String MemberName, Object[] Arguments, String[]
ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack) ...
Here is my code:
Public FunctionCtrl As Object
Function login_Call()
Try
Dim conn As Object
FunctionCtrl = CreateObject("SAP.Functions")
conn = FunctionCtrl.Connection
conn.System = XXX
conn.ApplicationServer = XXX
conn.SystemNumber = XXX
conn.Client = "XXX"
conn.user = XXX
conn.Password = XXX
conn.Language = XXX
'needed for frontend dialog
conn.RfcWithDialog = True
'log on with logon dialog
If Not conn.Logon(0, 1) Then
Dim WsShell
Dim intText As Integer
WsShell = CreateObject("WScript.Shell")
intText = WsShell.Popup("Logon not succesful." & vbCrLf & _
"will be closed automatically in one minute...", 60)
'conn = Nothing
Anmeldung_Call = False
Exit Function
End If
Anmeldung_Call = True
Catch ex As Exception
Anmeldung_Call = False
End Try
Me.Text = DateTime.Now.ToString()
End Function
Sub Open_IW73()
Dim BdcTable As Object
Dim RfcCallTransaction As Object
Dim Messages As Object
Dim count As Integer
'call transaction IW73
RfcCallTransaction = FunctionCtrl.Add("RFC_CALL_TRANSACTION")
RfcCallTransaction.Exports("TRANCODE") = "IW73"
RfcCallTransaction.Exports("UPDMODE") = "S"
BdcTable = RfcCallTransaction.Tables("BDCTABLE").....
The Error comes in this line: "RfcCallTransaction = FunctionCtrl.Add("RFC_CALL_TRANSACTION")
"
Thank you
I've had the same error. People suggested different fixes like using SAP.functions.Unicode.
What did it for me was simply changing to "RFC_CALL_TRANSACTION_USING". I'm not sure of the exact difference between these commands, so be careful with that. So far it has been working for me though.

Remove last element from array

How to remove the last element from an array in VB.NET. I need to split the street and housenumber.
STREET
Split the address on spaces
Remove last element (missing in the code)
Join array
NUMBER
Split the address on spaces
get last element
My code:
'split address
Dim addressArray() As String = args.Content.Split(" ")
'remove last element and return the joined array
Return String.Join(" ", addressArray.Remove(addressArray.Length() - 1))
Dim foo() As String = "This is a test".Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
Array.Resize(foo, foo.Length - 1)
Dim s As String = String.Join(" ", foo)
or use lists
Dim foo As New List(Of String)
foo.AddRange("This is a test".Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
foo.RemoveAt(foo.Count - 1)
Dim s As String = String.Join(" ", foo)
As far as using LINQ and performance, judge for yourself
Public Class Form1
'to LINQ or not to LINQ
'judge for yourself
Dim stpw As New Stopwatch
Private Sub Button1_Click(sender As System.Object, _
e As System.EventArgs) Handles Button1.Click
Dim ipsumA() As String = New String() {"Lorem", "ipsum", "dolor", "sit", _
"amet", "consectetur", "adipisicing", _
"elit", "sed", "do", "eiusmod", _
"tempor", "incididunt", "ut", "labore", _
"et", "dolore", "magna", "aliqua", "Ut", _
"enim", "ad", "minim", "veniam", "quis", _
"nostrud", "exercitation", "ullamco", _
"laboris", "nisi", "ut", "aliquip", "ex", _
"ea", "commodo", "consequat", "Duis", "aute", _
"irure", "dolor", "in", "reprehenderit", "in", _
"voluptate", "velit", "esse", "cillum", "dolore", _
"eu", "fugiat", "nulla", "pariatur", "Excepteur", _
"sint", "occaecat", "cupidatat", "non", "proident", _
"sunt", "in", "culpa", "qui", "officia", "deserunt", _
"mollit", "anim", "id", "est", "laborum"}
Const tries As Integer = 100000
Debug.WriteLine("")
stpw.Reset()
stpw.Start()
For x As Integer = 1 To tries
Dim s As String = arrayTake(ipsumA)
Next
stpw.Stop()
Debug.WriteLine(stpw.ElapsedTicks.ToString)
stpw.Reset()
stpw.Start()
For x As Integer = 1 To tries
Dim s As String = arrayRsz(ipsumA)
Next
stpw.Stop()
Debug.WriteLine(stpw.ElapsedTicks.ToString)
End Sub
Private Function arrayRsz(test As String()) As String
Array.Resize(test, test.Length - 1)
Return String.Join(" ", test)
End Function
Private Function arrayTake(test As String()) As String
Return String.Join(" ", test.Take(test.Length - 1))
End Function
End Class
You can't remove items from an array. The size of an array is decided when you create it, and can't be changed.
You can create a result that contains the items from the array except the last one:
Return String.Join(" ", addressArray.Take(addressArray.Length() - 1))
Edit:
If you are concerned about performance, you should not do any Split or Join at all, but simply get the parts of the string using simple string operations:
Dim pos As Integer = args.Content.LastIndexOf(" "C)
Dim street As String = args.Content.Substring(0, pos)
Dim number As String = args.Content.Substring(pos + 1)
This is at least ten times faster than any other method presented here.
Edit 2:
Here is the performance test code (C#):
Dim time As Performance = New Performance(1000000, 6)
Dim address As String = "aölskdjf öawe öofij 42"
Console.WriteLine(time.Take("SplitTakeJoin", Sub()
Dim parts As String() = address.Split(" "c)
Dim street As String = String.Join(" ", parts.Take(parts.Length - 1))
End Sub))
Console.WriteLine(time.Take("SplitResizeJoin", Sub()
Dim parts As String() = address.Split(" "c)
Array.Resize(parts, parts.Length - 1)
Dim street As String = String.Join(" ", parts)
End Sub))
Console.WriteLine(time.Take("Substring", Sub()
Dim street As String = address.Substring(0, address.LastIndexOf(" "c))
End Sub))
Output:
SplitTakeJoin 0,000511 ms.
SplitResizeJoin 0,000323 ms.
Substring 0,000031 ms.
using this performance test class:
Public Class Performance
Private _iterations As Integer
Private _displayDigits As Integer
Private _emptyTime As TimeSpan
Public Sub New(ByVal iterations As Integer, ByVal displayDigits As Integer)
_iterations = iterations
_displayDigits = displayDigits
_emptyTime = TimeSpan.Zero
_emptyTime = Take(Sub()
End Sub)
End Sub
Private Function Take(ByVal action As Action) As TimeSpan
Dim w As Stopwatch = Stopwatch.StartNew()
For i As Integer = 0 To _iterations - 1 Step 10
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Action()
Next
w.Stop()
Return w.Elapsed - _emptyTime
End Function
Public Function Take(ByVal title As String, ByVal action As Action) As String
Dim Time As TimeSpan = Take(action)
Return title + " " + (Time.TotalMilliseconds / Convert.ToDouble(_iterations)).ToString("N" + _displayDigits.ToString()) + " ms."
End Function
End Class
You could also try using Redim Preserve. These statements are carry overs from the Visual Basic 6.0 days and are not considered the .NET way of doing things, but it is another option. There may be performance issues though according to this article.
Redim Preserve addressArray(addressArray.Length - 1)
Actually to delete the last item of array you would have to:
Redim Preserve addressArray(addressArray.Length - 2)
since they are zero based and the length is one based.
This will return all but the last "word/number" in a String as an array of Strings.
Return args.content.Split(" ").Take((args.content.Split(" ").Count - 1)).ToArray()