Create strings on the fly using VB.NET - vb.net

I'm trying to create a number of strings based on one long string that i'm passing.
Basically this is an example of my long string
StrMain = AL123456 - PR123456 - RD123456 - LO123456
So in this case I want to create 4 separate strings.
Str1 = AL123456
Str2 = PR123456
Str3 = RD123456
Str4 = LO123456
But there isn't always that many or there may be more so I need to count how many - there are and with that then create the amount strings needed.
Any ideas?
Thanks
Jamie

Let we have:
var input = "AL123456 - PR123456 - RD123456 - LO123456"
then
input.Split('-');
will return
{ "AL123456 ", " PR123456 ", " RD123456 ", " LO123456" }
i.e. with leading and trailing spaces.
So you need trim each:
using System.Collections.Generic;
using System.Linq;
IEnumerable<string> result = input.Split('-').Select(s => s.Trim());
(Select() requires .NET 3.5+)
Or just split by " - ":
var result = input.Split(new string[] { " - " }, StringSplitOptions.None);
or using VB.NET syntax:
Dim result As String() = input.Split({ " - " }, StringSplitOptions.None)
I guess VB.NET has next syntax for for-each:
For Each str As String In result
Response.Write(str) ' or use str in other context '
End For

You could use the Split function:
Dim tokens As String() = "AL123456 - PR123456 - RD123456 - LO123456".Split("-"C)
or if you want to use a string as separator:
Dim tokens As String() = "AL123456 - PR123456 - RD123456 - LO123456".Split({" - "}, StringSplitOptions.RemoveEmptyEntries)

Use the split function
This is the use i recommend is below, you can adapt it by either:
adding more separators (add strings to the separator array like this: New String() {" - ", " _ "} )
removing empty entries (not necessary, but usually useful)
Dim MyString As String = "value1 - value2 - value3 - - value4"
Dim results As String() = MyString.Split(New String() {" - "}, StringSplitOptions.RemoveEmptyEntries)
' you get an array with 4 entries containing each individual string

Related

VB.net Html convertor error giving no change?

net language.
and I would like to replace the html first tags and keep the structure of the text, I have tried this code below from the website https://beansoftware.com/ASP.NET-Tutorials/Convert-HTML-To-Plain-Text.aspx
Dim html As String = "<div class='WordSection1'><p class='MsoNormal'>"
Dim final_result As String
Dim sbhtml As StringBuilder = New StringBuilder(html)
Dim OldWords() As String = {" ", "&", """, "<", ">", "®", "©", "•", "™"}
Dim NewWords() As String = {" ", "&", """", "<", ">", "®", "©", "•", "™"}
For i As Integer = 0 To i < OldWords.Length
sbhtml.Replace(OldWords(i), NewWords(i))
Next i
Console.WriteLine($"result after loop : {sbhtml}")
sbhtml.Replace("<br>", "\n<br>")
sbhtml.Replace("<br ", "\n<br ")
sbhtml.Replace("<p ", "\n<p ")
final_result = Regex.Replace(sbhtml.ToString(), "<[^>]*>", "")
Console.WriteLine(final_result)
However the output come back as the same as the string
The for-statement is wrong. It should be
For i As Integer = 0 To OldWords.Length - 1
Probably some C# syntax leaked over.
Why didn't you append the sbhtml.Replace("<br>", "\n<br>") and following lines to the OldWords and NewWords? They are technically not any different.
By using tuples, you can put the old and new words into the same array and use a For-Each-loop
I suggest the following approach
Dim html As String =
"<div class='WordSection1'>aaa<br>bbb<p class='MsoNormal'>"
Dim final_result As String
Dim sbhtml As StringBuilder = New StringBuilder(html)
Dim Substitutions() As (old As String, repl As String) = {
(" ", " "), ("&", "&"), (""", """"), ("<", "<"),
(">", ">"), ("®", "®"), ("©", "©"), ("•", "•"),
("™", "â„¢"), ("<br>", "\n<br>"), ("<br ", "\n<br "), ("<p ", "\n<p ")}
For Each subst In Substitutions
sbhtml.Replace(subst.old, subst.repl)
Next
Console.WriteLine($"result after loop : {sbhtml}")
final_result = Regex.Replace(sbhtml.ToString(), "<[^>]*>", "")
Console.WriteLine(final_result)
The HtmlAgilityPack does a very good job in HTML manipulation and is very reliable. You would do something like
Dim plainText As String = HtmlUtilities.ConvertToPlainText(html)
See Install and manage packages in Visual Studio using the NuGet Package Manager for the easy installation of the HtmlAgilityPack.

how to replace multiple range of white space with comma in VB?

How do i remove multiple white space with a comma
String str="one two "
Need output like str="one,two"
Dim Text As String = str.Trim.Replace("\s{2,}", ",")
Thank you.
String.Split and String.Join could be used here
Dim values = str.Split(new String() { " " }, StringSplitOptions.RemoveEmptyEntries)
Dim result = String.Join(",", values)
str = str.trimEnd.replace(" ", ",")

Substring and return list of comma separated characters

Domain\X_User|X_User,Domain\Y_User|Y_User,
I'm using a SSRS report and I'm receiving the above value, I want to write visual basic function in the report ( Custom code) to split the above string and return the following value:
X_User,Y_User
I tried to write this code inside a custom code of the report body:
Public Function SubString_Owner(X As String) As String
Dim OwnerArray() As String = Split(X, ",")
Dim Names As String
Dim i As Integer = 0
While i <= OwnerArray.Length - 1
Dim NamesArr As String() = Split(OwnerArray(0), "|")
Names = NamesArr(1) + ","
i += 1
End While
Return Names
End Function
The problem is when trying to split OwnerArray(i), it gives an error but when using a fixed value, like zero, it builds fine. Can anyone figure out why this is?
Here is a more generic solution that will work with any number of items:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s))
Dim usersWithoutDomains As IEnumerable(Of String) = domainsAndUsers.Select(Function(s) s.Remove(0, s.IndexOf("\") + 1))
Dim users As IEnumerable(Of String) = usersWithoutDomains.Select(Function(s) s.Remove(s.IndexOf("|")))
Dim result As String = users.Aggregate(Function(s, d) s & "," & d)
Or if you want it as a single-line function, here:
Function Foo(sourceString As String) As String
Return sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s)).Select(Function(s) s.Remove(0, s.IndexOf("\") + 1)).Select(Function(s) s.Remove(s.IndexOf("|"))).Aggregate(Function(s, d) s & "," & d)
End Function
EDIT:
You may have to add Imports System.Linq to the top. Not sure if SSRS can use LINQ or not. If not, then here is a similar solution without LINQ:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c)
Dim usersWithoutDomains As String = String.Empty
For Each domainUser As String In domainsAndUsers
usersWithoutDomains &= domainUser.Remove(0, domainUser.IndexOf("\") + 1) & ","
Next
Dim strTest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User"
MsgBox(strTest.Split("|")(0).Split("\")(1) & " " & strTest.Split("|")(1).Split("\")(1))
Here's a simple way that will work with variable data as long as the pattern you've shown is strongly followed:
Imports System.Linq
Dim strtest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
'This splits the string according to "|" and ",". Now any string without _
a "\" is the user and Join adds them together with `,` as a delimiter
Dim result As String = Join((From s In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Where Not s.Contains("\")
Select s).ToArray, ",")
Just in case LINQ is unavailable to you here's a different way to the same results without LINQ:
Dim result As String = ""
For Each s As String In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
If Not s.Contains("\") Then
result += s & ","
End If
Next
result = result.TrimEnd(",".ToCharArray)

loop through 2 strings and combine VB 2010

i have a simple task i think
my code generates 2 strings
string A (separated by line feeds)
1
2
3
4
String B (separated by line feeds)
5
6
7
8
i am trying to figure out how to combine these separate strings into one as if they were two columns next to each other, separated by a comma
the result would be string C
1,5
2,6
3,7
4,8
Thanks!
How about something like?
Dim A As String = "1" & vbCrLf & "2" & vbCrLf & "3" & vbCrLf & "4"
Dim B As String = "5" & vbCrLf & "6" & vbCrLf & "7" & vbCrLf & "8"
Debug.Print(A)
Debug.Print(B)
Dim tmp As New List(Of String)
tmp.AddRange(A.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries))
Dim values() As String = B.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
For i As Integer = 0 To values.Length - 1
If i <= tmp.Count - 1 Then
tmp(i) = tmp(i) & "," & values(i)
Else
tmp.Add("," & values(i))
End If
Next
Dim C As String = String.Join(vbCrLf, tmp.ToArray)
Debug.Print(C)
Convert both strings to char[] (Char() - character array) (string.ToCharArray()).
Iterate thru the arrays.
You will need to check boundary conditions (e.g. what if the strings are different lengths).
'first string
Dim a As String = "abcd"
'second string
Dim b As String = "defghijk"
'Remove Line feeds
Dim tempA As String = a.Replace(vbLf, "")
Dim tempB As String = a.Replace(vbLf, "")
'Get the string with the larger size.
Dim largerSize As Integer = If(tempA.Length > tempB.Length, tempA.Length, tempB.Length)
'We use a string builder to build our new string
Dim sb As New StringBuilder()
'Loop on the larger size and only insert if inside range of string
For i As Integer = 0 To largerSize - 1
If i < tempA.Length Then
sb.Append(a(i))
sb.Append(",")
End If
If i < tempB.Length Then
sb.Append(b(i))
End If
sb.Append(vbLf)
Next
'this is the result
Dim combined As String = sb.ToString()
Edit answer to remove line feeds
Another Edit after string result edited
Another edit to make it VB.NET
I would use the wonderful Linq Zip! (I would first String.Split the 2 strings with the line-feed character) and then
Dim column1() As String = {"1", "2", "3", "4"}
Dim column2() As String = {"5", "6", "7", "8"}
Dim mixed= column1.Zip(column2, Function(first, second) first & "," & second)
edit:
oh, and then, if you want to have it back into 1 string, you can either use String.Join but Linq is fun too! So you can write :
Dim mixed= column1.Zip(column2, Function(first, second) first & "," & second)
.Select(i => i.Boo)
.Aggregate((i, j) => i + vbLf + j)
Did I mention that Linq is fun?

Split string by " " in VB.NET

Let’s say that this is my string:
1 2 3
I want to split the string by " " (space) and display every time part of my string.
This will do what you need:
Dim str As String = "1 2 3"
Dim strarr() As String
strarr = str.Split(" "c)
For Each s As String In strarr
MessageBox.Show(s)
Next