How can I trim a string in BASIC? - 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.

Related

Put a space in front of every capital letter in a string

I want to put spaces before each capital letter in a string.
So turn this: TheQuickBrownFox
into this: The Quick Brown Fox
This is the code I have so far: it finds uppercase chars in the string and shows each upper letter in a Message Box.
I can't figure out where to go from here:
Dim input As String = "TheQuickBrownFox"
For i As Integer = 0 To input.Length - 1
Dim c As Char = input(i)
If Char.IsUpper(c) Then
MsgBox(c)
End If
Next
I've googled around but I wasn't able to find a solution for visual basic.
A couple of example using LINQ:
Imports System.Linq
Imports System.Text
Dim input As String = "TheQuickBrownFox"
In case you don't know it, a String is a collection of Chars, so you can iterate the string content using a ForEach loop (e.g., For Each c As Char In input).
▶ Generate a string from an collection of chars (Enumerable(Of Char)), excluding the first uppercase char if it's the first in the string.
The second parameter of a Select() method, when specified (in Select(Function(c, i) ...)), represents the index of the element currently processed.
String.Concat() rebuilds a string from the Enumerable(Of Char) that the Select() method generates:
Dim result = String.Concat(input.Select(Function(c, i) If(i > 0 AndAlso Char.IsUpper(c), ChrW(32) + c, c)))
The same, not considering the position of the first uppercase char:
Dim result = String.Concat(input.Select(Function(c) If(Char.IsUpper(c), ChrW(32) + c, c)))
▶ With an aggregation function that uses a StringBuilder as accumulator (still considering the position of the first uppercase char).
When processing strings, a StringBuilder used as storage can make the code more efficient (creates way less garbage) and more performant.
See, e.g., here: How come for loops in C# are so slow when concatenating strings?
➨ Note that I'm adding an Array of chars to the StringBuilder:
Dim result = input.Aggregate(New StringBuilder(),
Function(sb, c) sb.Append(If(sb.Length > 0 AndAlso Char.IsUpper(c), {ChrW(32), c}, {c})))
➨ result is a StringBuilder object: extract the string with result.ToString().
Or, as before, without considering the position:
Dim result = input.Aggregate(New StringBuilder(),
Function(sb, c) sb.Append(If(Char.IsUpper(c), {ChrW(32), c}, {c})))
▶ The two example above are somewhat equivalent to a simple loop that iterates all chars in the string and either creates a new string or uses a StringBuilder as storage:
Dim sb As New StringBuilder()
For Each c As Char In input
sb.Append(If(sb.Length > 0 AndAlso Char.IsUpper(c), {ChrW(32), c}, {c}))
Next
Change the code as described before if you want to add a space to the first uppercase Char without considering its position.
Yet another option is a language extension method.
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Demo()
Console.ReadLine()
End Sub
Private Sub Demo()
Dim data = New List(Of String) From
{
"ThisIsASentence",
"TheQuickBrownFox",
"ApplesOrangesGrapes"}
data.ForEach(Sub(item) Console.WriteLine($"{item,-25}[{item.SplitCamelCase}]"))
End Sub
End Module
Public Module StringExtensions
<Runtime.CompilerServices.Extension>
Public Function SplitCamelCase(sender As String) As String
Return Regex.Replace(Regex.Replace(sender,
"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2"),
"(\p{Ll})(\P{Ll})",
"$1 $2")
End Function
End Module
You can use a regular expression:
Dim input = "TheQuickBrownFox"
Dim withSpaces = Regex.Replace(a, "(?<!^)([A-Z])", " $1")
The regex finds any uppercase A-Z that are not preceded by the start of the string and captures it into a group. The replacement takes the group content and prefixes a space
If you don't want to use the negative lookbehind, you can trim the result:
Dim withSpaces = Regex.Replace(a, "([A-Z])", " $1").TrimStart()
Or don't trim if you don't care that the string starts with a space
To expand on your code:
Dim input As String = "TheQuickBrownFox"
Dim outputSB as new StringBuilder
For i As Integer = 0 To input.Length - 1
Dim c As Char = input(i)
If Char.IsUpper(c) Then
outputSB.Append(" ")
'MsgBox(c)
End If
outputSB.Append(c)
Next
Console.Writeline(outputSB.ToString())

Split String New Line After 3 Space in VB.net

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

How do i get part of string after a special character?

I have a column where i pickup increasing numbering values, and their format is xx_yy
so the first is 1_0, second 1_1 and so forth, no we are at 23_31
I want to get the right side of the string, and i am already getting the left side correctly.
using
newActionId = Left(lastActionID, (Application.WorksheetFunction.Find("_", lastActionID, 1) - 1))
i wish to do the following, human writing below
nextSubid = entire stringvalue AFTER special character "_"
I tried just switching left to right, didnt go so well, do you have a suggestion?
You can use Split function to get the relevant text.
Syntax: Split(expression, [ delimiter, [ limit, [ compare ]]])
Option Explicit
Sub Sample()
Dim id As String
Dim beforeSplChr As String
Dim afterSplChr As String
id = "23_31"
beforeSplChr = Split(id, "_")(0)
afterSplChr = Split(id, "_")(1)
Debug.Print beforeSplChr
Debug.Print afterSplChr
End Sub
Another way
Debug.Print Left(id, (InStrRev(id, "_", -1) - 1)) '<~~ Left Part
Debug.Print Right(id, (InStrRev(id, "_", -1) - 1)) '<~~ Right Part
Even though Siddharth Rout has given what can probably be considered a better answer here, I felt that this was worth adding:
To get the second part of the string using your original method, you would want to use the Mid function in place of Left, rather than trying to use Right.
Mid(string, start, [ length ])
Returns length characters from string, starting at the start position
If length is omitted, then will return characters from the start position until the end of the string
newActionId = Mid(lastActionID, Application.WorksheetFunction.Find("_", lastActionID, 1) + 1)
Just for fun (Split is the way to go here), an alternative way using regular expressions:
Sub Test()
Dim str As String: str = "23_31"
With CreateObject("VBScript.RegExp")
.Global = True
.Pattern = "\d+"
Debug.Print .Execute(str)(0) 'Left Part
Debug.Print .Execute(str)(1) 'Right Part
End With
End Sub
Btw, as per my comment, your first value could also be achieved through:
Debug.Print Val(str)
Split function of string is very usefull for this type of query.
Like:
String s = "23_34";
String left = s.split("_")[0];
String right = s.split("_")[1];
Or you can also use combination of indexOf and substring method together.
String left = s.substring(0,s.indexOf('_')+1)
String right = s.substring(s.indexOf('_'));

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.

VBA Regular Expression Mail

I want to split a string into 3 parts. For example i have a email adress like
testuser#gamil.com
and i want to split it into
testuser
gamil
.com
with left, right and mid (str) i only can extract a string if is a fixed lenght.
Has anybody some ideas to make it?
with left, right and mid (str) i only can extract a string if is a fixed length.
This is not actually true, because you can also use the len function to get the length of the string.
Dim L as Integer
L = Len("testuser#gamil.com")
MsgBox L
You can also use the Instr (and InstrRev, reversed) function to find the index of a particular character or substring.
Dim I as Integer
I = Instr("testuser#gamil.com", "#")
So, for your case, a custom function without regex will return an array of three items:
Function SplitEmail(email$)
'Function returns an array like:
' {"username", "domain", "tld"}
Dim Dot As Integer, At As Integer
Dot = InStrRev(email, ".")
At = InStr(email, "#")
Dim ret(1 To 3) As String
ret(1) = Left(email, At - 1)
ret(2) = Mid(email, At + 1, Dot - At - 1)
ret(3) = Mid(email, Dot + 1)
SplitEmail = ret
End Function
To get the username part, you could do:
Dim some_email$
some_email = "testuser#gamil.com"
MsgBox SplitEmail(some_email)(1)

Resources