Split String New Line After 3 Space in VB.net - string

i have problem to split string into newline in vb.net.
right now i can make it to split by a single space.i want split new line after 3 space.
Dim s As String = "SOMETHING BIGGER THAN YOUR DREAM"
Dim words As String() = s.Split(New Char() {" "c})
For Each word As String In words
Console.WriteLine(word)
Next
output :
SOMETHING
BIGGER
THAN
YOUR
DREAM
Desire output :
SOMETHING BIGGER THAN
YOUR DREAM

Another alternative added to existing efficient answers might to be:
Dim separator As Char = CChar(" ")
Dim sArr As String() = "SOMETHING BIGGER THAN YOUR DREAM".Split(separator)
Dim indexOfSplit As Integer = 3
Dim sFinal As String = Join(sArr.Take(indexOfSplit).ToArray, separator) & vbNewLine &
Join(sArr.Skip(indexOfSplit).ToArray, separator)
Console.WriteLine(sFinal)

You can split your input string, then loop the array of parts generated and add them to a StringBuilder object.
When you have read a number of parts that is multiple of a defined value, (wordsPerLine, here), you append vbNewLine to the current part.
When the loop completes, print the content of the StringBuilder to the Console:
Dim input As String = "SOMETHING BIGGER THAN YOUR DREAM, NOT MORE THAN YOUR ACCOUNT BALANCE"
Dim wordsPerLine As Integer = 3
Dim wordsCounter As Integer = 1
Dim sb As StringBuilder = New StringBuilder()
For Each word As String In input.Split()
sb.Append(word & If(wordsCounter Mod wordsPerLine = 0, vbNewLine, " "))
wordsCounter += 1
Next
Console.WriteLine(sb.ToString())
Prints:
SOMETHING BIGGER THAN
YOUR DREAM, NOT
MORE THAN YOUR
ACCOUNT BALANCE

Instead of using split, you might capture 3 words in a capturing group and match the trailing whitespace chars.
In the replacement use the group followed by a newline.
Pattern
(\S+(?:\s+\S+){2})\s*
That will match:
( Capture group 1
\S+ Match 1+ non whitespace chars
(?:\s+\S+){2} Repeat 2 times matching 1+ whitespace chars and 1+ non whitespace chars
) Close group 1
\s* Match trailing whitespace chars
.NET Regex demo | VB.NET demo
Example code
Dim s As String = "SOMETHING BIGGER THAN YOUR DREAM"
Dim output As String = Regex.Replace(s, "(\S+(?:\s+\S+){2})\s*", "$1" + Environment.NewLine)
Console.WriteLine(output)
Output
SOMETHING BIGGER THAN
YOUR DREAM

String.Join has an overload that will help you.
First parameter is the character to use between elements of your array.
Second parameter is the array you wish to join.
Third parameter is the starting position, for the first line in your desired output this would be the element at index 0.
Fourth parameter is the length to use, for the first line we want three array elements.
Private Sub OPCode()
Dim s As String = "SOMETHING BIGGER THAN YOUR DREAM"
Dim words As String() = s.Split(New Char() {" "c})
Dim line1 As String = String.Join(" ", words, 0, 3)
Console.WriteLine(line1)
Dim line2 As String = String.Join(" ", words, 3, words.Length - 3)
Console.WriteLine(line2)
End Sub

Related

Extract Excel VBA filenames from string

I want to extract file names from a string. The length of the string and the length of the file name are always different.
Must be done with VBA!
String:
href ist gleich: "abc/db://test.pdf|0|100">Bsp.:
I would like that:
test.pdf
I do not know how to proceed.
It would also be nice if the script could extract multiple filenames from a string.
Zb:
String:
href ist gleich: "abc//db://test.t.pdf|0|100" "db://test1.pdf|0|100">Bsp.
I would like that:
test.t.pdf test1.pdf
Sub testExtractFileName()
Debug.Print extractFileName("file://D:/ETVGI_556/Carconfigurator_file/carconf_d.pdf", "//")
Debug.Print extractFileName("abc//db://test.t.pdf|0|100")
Debug.Print extractFileName("db://test1.pdf|0|100")
End Sub
Function extractFileName(initString As String, Optional delim As String) As String
Dim necString As String
necString = left(initString, InStr(initString, ".pdf") + 3)
necString = Right(necString, Len(necString) - InStrRev(necString, _
IIf(delim <> "", delim, "/")) - IIf(delim <> "", Len(delim) - 1, 0))
extractFileName = necString
End Function
The single condition is that in front of the file name (all the time) to exist "//" characters in the initial string. And of course the file extension to all the time to be .pdf. If not, this extension is required and the function can be easily adapted...
The function returns full name if the second (optional) parameter will be "//" or just the file name (without path) if it is omitted.
One option could be using a pattern where you would match the preceding / and capture in a group 1+ word characters \w+ followed by .pdf
Your value is in capturing group 1.
/(\w+\.pdf)
See a regex demo
If you want to have a broader match than \w you could extend what you do want to match using a character class or use a negated character class [^ to match any char except the listed in the character class.
In this case the negated character class [^/|"\s] would match any char except / | " or a whitespace character \s
/([^/|"\s]+\.pdf)
See another regex demo
Try this and edit it according to your needs. At least it was designed for two of your examples.
Dim sStringToFormat As String
Dim i As Integer
Dim vSplit As Variant
Dim colFileNames As Collection
Dim sFormattedString As String
Set colFileNames = New Collection
sStringToFormat = "href ist gleich: ""abc//db://test.t.pdf|0|100"" ""db://test1.pdf|0|100"">Bsp."
vSplit = Split(sStringToFormat, "/")
For i = LBound(vSplit) To UBound(vSplit)
If InStr(vSplit(i), ".") > 0 Then
sFormattedString = Split(vSplit(i), "|")(0)
sFormattedString = Split(sFormattedString, "<")(0)
sFormattedString = Split(sFormattedString, ">")(0)
colFileNames.Add sFormattedString
End If
Next i

Insert a character in string (indexof)

what I want to do is insert a desired character like a "space" into a desired string like "123456789" at a specific point. Example: insert a space at the position 5 in the string 123456789 = 1234 56789. Here is my code:
Dim str As String = sum2.Text '123456789
Dim insStr As String = " " 'space
Dim strRes As String = str.Insert(5, insStr) '5th position
the code looks fine and i dont get any errors when i use it or run it but it will not add the space at the 5th position so i need some help!
You must not that the startIndex in String.Insert(Integer, String) is zero based. That means if your intention is to insert a space in the 5th position, you will have to adjust that by -1:
Dim insertPosition = 5 ' Assuming this came from the user who says put it in position 5
Dim inStr = " "
Dim strRes = str.Insert(insertPosition - 1, inStr) ' assuming your str already had a value.
That will insert the space between 4 and 5 and will produce
1234 56789
I saw in one your comments that you might want to insert spaces in positions 1,5,7. In that case, you will have to do it in reverse, starting with the largest position, to the smallest. This is of cause assuming that you wanted
_1234_6_89
I have used underscores to represent spaces so that you can see it better.
Before working with that, ensure that your string has enough characters to be indexed by your index otherwise you'll get a ArgumentOutOfRangeException.

Split a long string by using a complete word

I'm splitting a long string like shown below wherever it finds 'END' keyword:
string_end.Split(New String() {"END"}, StringSplitOptions.None)
This would perfectly split the string into multiple parts wherever it finds 'END' . But the problem arises when a string contains the word 'RECOMMENDED'. It would split it as 'RECOMM' and 'ED'. I want it to split by searching for the whole word, so that words like 'RECOMMENDED' stays as it is. Kindly help.
C# and VB.NET codes would suffice.
You can use Regex.Split to solve this:
Dim rgx As New Regex("\bEND\b")
Dim input As String = "RECOMMENDED AND THE END OF A STRING END"
Dim result() As String = rgx.Split(input)
'Output:
'-----------------------------
'result = {Length=3}
'(0) = "RECOMMENDED AND THE "
'(1) = " OF A STRING "
'(2) = ""
The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.
There are three different positions that qualify as word boundaries:
Before the first character in the string, if the first character is a word character.
After the last character in the string, if the last character is a word character.
Between two characters in the string, where one is a word character and the other is not a word character.
source: http://www.regular-expressions.info/wordboundaries.html
Why you shouldn't use spaces on a String.Split?
Dim input As String = "RECOMMENDED AND THE END OF A STRING END"
Dim res() As String = input.Split(New String() {" END "}, StringSplitOptions.None)
'Output:
'----------------------------
'res = {Length=2}
'(0) = "RECOMMENDED AND THE"
'(1) = "OF A STRING END"
The split doesn't work with this code only the word END is a single word with surrounded space. But the word can be surrounded by another character or could be the beginning or end of a string:
END TEST - doesn't work
TEST END - doesn't work
TEST END, HELLO WORLD - doesn't work
...
If your simply looking for the word: END then simply add a white-space before and after:
string_end.Split(New String() {" END "}, StringSplitOptions.None)
After I don't recommend using split to include or exclude a line.
A cleaner solution would simply to do
For Each line As String In Lines
If line.Contains(" END ") Then
'Do Stuff
End If
Next
You could also use Regex but that depends if you are familiar with it.
Private _pattern As New Regex("\bEND\b", RegexOptions.Compiled)
For Each line As String In Lines
Dim matches As MatchCollection = _pattern.Matches(line)
If matches.Count <> 0 Then
'Do Stuff
End If
Next

How can I trim a string in BASIC?

How do trim off characters in a string, by how much you want?
For example, say your string is "Tony", but you wanted to display "ny" by trimming of the first two characters, how can this be done?
Sub Main()
Dim s As String
Dim Result As String
s = "Tony"
Result = LTrim(s)
msgbox(Result)
I have this so far using the LTrim function, so how do you specify by how much you want to cut to just display "ny" in the MessageBox?
You don't want LTrim. You want Right:
Result = Right(s, Len(s) - 2);
This will take all but the two left-most characters of s.
You could use the additional string functions to do the same thing,
for example:
X$ = RIGHT$(V$, 2) ' get the ending 2 chars of string
X$ = LEFT$(V$, 2) ' get the leading 2 chars of string
X$ = MID$(V$, 2, 2) ' get 2 chars from the inside of string
Well... If I was trying to clip off the beginning of a string, I would use two functions: StrReverse, and Remove.
I would first reverse the string, then use the remove function to cut off what is now the end, Then flip the remaining string back to it's original state using the reverse function again.
The code would look something like this:
Dim s As String = "Anthony"
Dim index As Integer = 2
Debug.Print(StrReverse(StrReverse(s).Remove(2)))
The output of this would be "ny" and the length will correspond to the index.

Insert a character into a string at a specified index

So I have an array of indexes of characters in a string that I wish to insert a character before, how do i easily insert a character before each index? So for example:
"The big brown fox ... "
the positions
array = 4,9
the character to insert ','
the result: "The, big, brown fox ..."
Is there a method that provides such an easy utility?
String.insert(originalStr, index, stringToInsert) for example???
Update
The example I provided is just an example implementation. I also may want to do the following:
orginalText = "some text with characters like ; : } <"
in which I may want to insert "\" with the result being:
result = "some text with characters like \; : } \<"
This is hacky and a bit rushed but try this:
Dim sString: sString = "the something something"
Dim position: position = 1
Dim character: character = "F"
if position = 0 then
sString = character + Left(Mid(sString, 1), Len(sString) + 1)
else
sString = Left(sString, position) + character + Left(Mid(sString, position), Len(sString) - position + 1)
end if
Assuming that the indexes are sorted, loop backwards and insert each character.
For lngPos = UBound(alngPositions) to 0 step -1
strText = Left(strText, alngPositions(lngPos) - 1) + "," + Mid(strText, alngPositions(lngPos))
Next
Note that with your example data it will of course produce the string "The, big ,brown fox ... ". The indexes are not pre-added to match the position in the resulting string, are they?
Edit:
An alternative that would be faster for large strings, is to split up the string at the index positions into an array, then join the strings with commas in between:
Dim astrSubstrings(UBound(alngPositions) + 1)
lngLeft = 1
For lngPos = 0 to UBound(alngPositions)
astrSubstrings(lngPos) = Mid(strText, lngLeft, alngPositions(lngPos) - lngLeft)
lngLeft = alngPositions(lngPos)
Next
astrSubstrings(UBound(alngPositions) + 1) = Mid(strText, lngLeft)
strText = Join(astrSubstrings, ",")
I'm not a classic ASP user but you can use substring to get the part of the string up to the index where you have to insert the character, substring the other part of the string and take these two parts and build a new string doing part1 & "," & part2.
Hope it helps.
You should be able to use the split function based on the space between the words - this will return an array of words. You then put a comma after each item in the array and you can get to the requried string that you are looking for. Example here http://www.w3schools.com/VBscript/func_split.asp
It's been a while, but Mid(str, start, [end]) would be the way to go.

Resources