how to replace multiple range of white space with comma in VB? - vb.net

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(" ", ",")

Related

Insert a string at specified indexof position using VB.NET

I'm trying to insert the string " " or a blank space in a specified index on a textbox like so:
textbox = heybrowhatsup
I want to insert an " " on the indexes 4, 8 and 14, to get "hey bro whats up", but my code just won't work.
My code:
Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(15, insStr)
Dim str As String = sum2.Text
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr)
strRes = strRes.Insert(7, insStr)
strRes = strRes.Insert(12, insStr)
You must use strRes.Insert for second or more.
Any string manipulation creates a new String object. What you're doing is working perfectly in that it is creating a new String with the specified substring inserted at the specified position. As is always the case, if you want that String displayed in your TextBox then you must assign that String to the Text property of that TextBox.
The Space function is useful for formatting output and clearing data in fixed-length strings.
You can use space function as below.
Dim str As String = "heybrowhatsup"
Dim strRes As String = str.Insert(3, Space(1)).Insert(7, Space(1)).Insert(13, Space(1))
Or
You can do the same with insert function.
Dim str As String = "heybrowhatsup"
Dim insStr As String = " "
Dim strRes As String = str.Insert(3, insStr).Insert(7, insStr).Insert(13, insStr)

Remove only one newline from the end of string in vb.net

I have a string like below
test1
test2
test3
newline
newline
newline
here i am using s = s.TrimEnd(ControlChars.Cr, ControlChars.Lf) to remove the last newline only, but it's removing all three newline.
i want to remove only one last newline from the string if any
Thanks in advance...
you can try like:
if (s.EndsWith(Environment.NewLine)) {
s = s.Remove(s.LastIndexOf(Environment.NewLine)) }
Get last space and then get sub string.
Dim lastIndex = s.lastIndexOf(" ")
s = s.substring(0, lastIndex)
(Or)
Use split function
Dim s = "test1 test2 test3 newline newline newline"
Dim mySplitResult = myString.split(" ")
Dim lastWord = mySplitResult[mySplitResult.length-1]
we can do as below
Dim stringText As String() = "test1 test2 test3 newline newline newline"
Dim linesSep As String() = {vbCrLf}
Dim lines As String() = stringText.Split(linesSep, StringSplitOptions.None)
If stringText.EndsWith(vbCrLf) Then
Dim strList As New List(Of String)
strList.AddRange(lines)
strList.RemoveAt(lines.Length - 1)
lines = strList.ToArray
End If
it worked for me!!!!
Here you go.
s = s.substring(0, s.lastindexof(characterToBeRemoved))

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)

Split a string in VB.NET

I am trying to split the following into two strings.
"SERVER1.DOMAIN.COM Running"
For this I use the code.
Dim Str As String = "SERVER1.DOMAIN.COM Running"
Dim strarr() As String
strarr = Str.Split(" ")
For Each s As String In strarr
MsgBox(s)
Next
This works fine, and I get two message boxes with "SERVER1.DOMAIN.COM" and "Running".
The issue that I am having is that some of my initial strings have more than one space.
"SERVER1.DOMAIN.COM Off"
There are about eight spaces in-between ".COM" and "Off".
How can I separate this string in the same way?
Try this
Dim array As String() = strtemp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
Use this way:
Dim line As String = "SERVER1.DOMAIN.COM Running"
Dim separators() As String = {"Domain:", "Mode:"}
Dim result() As String
result = line.Split(separators, StringSplitOptions.RemoveEmptyEntries)
Here's a method using Regex class:
Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es not-running"}
For Each s In str
Dim regx = New Regex(" +")
Dim splitString = regx.Split(s)
Console.WriteLine("Part 1:{0} | Part 2:{1}", splitString(0), splitString(1))
Next
And the LINQ way to do it:
Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es not-running"}
For Each splitString In From s In str Let regx = New Regex(" +") Select regx.Split(s)
Console.WriteLine("Part 1:{0} | Part 2:{1}", splitString(0), splitString(1))
Next

Create strings on the fly using 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