How to Trim consecutive Characters VB.net - vb.net

I'm looking to trim (drop) consecutive characters, and everything in front of it in vb.net.
An example of the output:
*017834
^018730
%018411
What I'd like to do - is trim '01' and any character in front of it. So my desired output would be:
7834
8730
8411
I attempted to use
Dim charsToTrim() As Char = { "01"c}
However, you're only allowed to use 1 character at a time this way in vb.net. Since i may have "0" or "1", I can't break it up like this:
Dim charsToTrim() As Char = { "0"c,"1",c}

Function Trim01(ByVal input As String) As String
Dim pos = input.IndexOf("01")
Return If(pos >= 0, input.Substring(pos + "01".Length), input)
End Function

Related

Reading only first 1 to 2 integers in a for loop VBA

How do I read the first 1 to 2 integers of a string in a loop? I need to only parse the first integer or the second integer. For example, "8sdr" I only want to parse "8" and then for a "12sdr" I want to parse "12". I need this to be in a loop to be able to continuously parse only the first integers in a string. Thank you!
The following will return any given number of digits from the start of a string:
Function LeadingDigits(text As String, maxDigits As Integer) As String
Dim pos As Integer, c As String
Do Until pos >= maxDigits Or pos >= Len(text)
c = Mid$(text, pos + 1, 1)
If c < "0" Or c > "9" Then Exit Do
pos = pos + 1
Loop
LeadingDigits = Mid$(text, 1, pos)
End Function
Contrary to solutions that rely on IsNumeric() or Val(), this function does not get confused by strings that can be interpreted as numeric, but don't fall into the specification, such as
hexadecimal ("&habc" = 2748)
scientific notation ("3e4" = 30000)
+/- signs at the start of the string
decimal numbers ".5" = 0.5
Only decimal digits 0–9 at the start of the string are accepted.
The function returns a string, not a numeric type (like Integer) so that there can be a separate return value for "nothing found" (the empty string), and so that very long numbers can be returned that would not fit into a numeric data type.
If you need only up to two numbers that occur before a letter I would use RegEx for this:
Public Function FirstTwoNumbersFromStringBeforeLetter(ByVal textNumbers As String) As Long
Dim regEx
Set regEx = CreateObject("vbscript.regexp")
With regEx
.Global = True
.Pattern = "[a-z].*|\D"
FirstTwoNumbersFromStringBeforeLetter = Left(Val(.Replace(textNumbers, vbNullString)), 2)
End With
End Function

Shift letters to the end of a string Visual Basic

I'm trying to shift letters to the end of the word. Like the sample output I have in the image.
Using getchar and remove function, I was able to shift 1 letter.
mychar = GetChar(word, 1) 'Get the first character
word = word.Remove(0, 1) 'Remove the first character
input.Text = mychar
word = word & mychar
output.Text = word
This is my code for shifting 1 letter.
I.E. for the word 'Star Wars', it currently shifts 1 letter, and says 'tar WarsS'
How can I make this move 3 characters to the end? Like in the sample image.
intNumChars = input.text
output.text = mid(word,4,len(word)) & left(word,3)
I wanted it to be easy for you to read but you can set the intNumChars variable to the value in your text box and replace the 4 with intNumChars + 1 and the 3 with intNumChars.
The mid() function can return a section of text in the middle of a string mid(string,start,finish). The len() function returns the length of a string so that the code will work on texts that are different lengths. The left function returns characters from the left() of a string.
I hope this is of some help.
You could write a that as a sort of permute, which maps each char-index to a new place in the range [0, textLength[
In order to do that you'll have to write a custom modulus as the Mod operator is more a remainder than a modulus (from a mathematical point of view, regarding how negative are handled)
With that you just need to loop over your string indexes and map each one to it's "offsetted" value modulo the length of the text
' Can be made local to Shift method if needed
Function Modulus(dividend As Integer, divisor As Integer) As Integer
dividend = dividend Mod divisor
Return If(dividend < 0, dividend + divisor, dividend)
End Function
Function Shift(text As String, offset As Integer) As String
' validation omitted
Dim length = text.Length
Dim arr(length - 1) As Char
For i = 0 To length - 1
arr(Modulus(i + offset, length) Mod length) = text(i)
Next
Return new String(arr)
End Function
That way you can easily handle negative values or values greater than the length of the text.
Note, the same thing is possible with a StringBuilder instead of an array ; I'm not sure which one is "better"
Function Shift(text As String, offset As Integer) As String
Dim builder As New StringBuilder(text)
Dim length = text.Length
For i = 0 To length - 1
builder(Modulus(i + offset, length) Mod length) = text(i)
Next
Return builder.ToString
End Function
Using Gordon's code did the trick. The left function visual studio tried to create a stub of the function, so I used the fully qualified function name when calling it. But this worked perfectly.
intNumChars = shiftnumber.Text
output.Text = Mid(word, intNumChars + 1, Len(word)) & Microsoft.VisualBasic.Left(word, intNumChars)
n = 3
output.Text = Right(word, Len(word) - n) & Left(word, n)

Trimming begining of string in VB forms application

Here is an example of the string / variable i want to trim:
type="game" music-file="my-file.mp3" gts="false"
I would like to find the beginning / end of the following code and trim them off.
I do not know the string before / after, so i am not able to use replace("String", "") functions.
How would i trim the string to make it only show: music-file="my-file.mp3?
I would like the string to go into a text box.
I would like to trim the beginning and end if possible.
I would NOT like to use external libraries (DLLS)
I assume your keyword is music-file="
use InStr() to find your keyword example:
int keyWordPos = InStr(<your string>,<your keyword>) 'keyWordPos = 13
you will get the first position of keyword. Next, use it as start position to find the end of value(I mean the second " of music-file="my-file.mp3"). But, don't forget to add keyword length to skip the first ". Like this.
int endWordPos = Instr(keyWordPos + len(<your keyword>),<your string>,<your keyword>) 'Start at 25 and endWordPos = 36
After that, use SubString() to get your value.
string strVal = <String Variable>.SubString(keyWordPos,endWordPos - keyWordPos + 1)
Here the answer of mine.
string strText = "type='game' music-file='my-file.mp3' gts='false'"
string keyWord = "music-file='"
int keyWordPos = Instr(strText,keyWord) 'Should be 13
int endWordPos = Instr(keyWordPos + len(keyWord),strText,"""") 'Should be 36
string resultText = strText.SubString(keyWordPos,endWordPos - keyWordPos +1)
Dim text As String = "type='game' music-file='my-file.mp3' gts='false'"
text = ((text.Substring(text.IndexOf("music-file"))).Substring(0, (text.Substring(text.IndexOf("music-file"))).IndexOf(" gts="))).Trim

Break string up

I have a string that has 2 sections broken up by a -. When I pass this value to my new page I just want the first section.
An example value would be: MS 25 - 25
I just want to show: MS 25
I am looking at IndexOf() and SubString() but I can't find how to get the start of the string and drop the end.
This might help:
http://www.homeandlearn.co.uk/net/nets7p5.html
Basically the substring method takes 2 parameters. Start position and length.
In your case, the start position is 0 and length is going to be the position found by the IndexOf method -1.
For example:
Dim s as String
Dim result as String
s = "MS 25 - 25"
result = s.SubString(0, s.IndexOf("-")-1)
You could use the Split function on the hyphen.
.Split("-")
If you want to stay away from Split, you could use SubString
yourString.Substring(0, yourString.IndexOf("-") - 1)
EDIT
The above code will fail in the instances where there is no hyphen at all or the hyphen is in the beginning of the string, also when there are no spaces surrounding the hyphen, the full leading substring will not be returned. Consider using this for safety:
Dim pos As Integer
Dim result As String
pos = yourString.IndexOf("-")
If (pos > 0) Then
result = yourString.Substring(0, pos)
ElseIf (pos = 0) Then
result = String.Empty
Else
result = yourString
End If

Substring starting at specific character count

How would you select the last part of a string starting at a specific character count.
For example I would like to get all text after the 3rd comma. but I get an error saying
"StartIndex cannot be less than zero."
Dim testString As String = "part, description, order, get this text, and this text"
Dim result As String = ""
result = testString.Substring(testString.IndexOf(",", 0, 3))
Heres my two cents:
string.Join(",", "aaa,bbb,ccc,ddd,eee".Split(',').Skip(2));
The code "testString.IndexOf(",", 0, 3)" does not find the 3rd comma. It find the first comma starting at position 0 looking at the first 3 positions (i.e. character positions 0,1,2).
If you want the part after the last comma use something like this:
Dim testString As String = "part, description, order, get this text"
Dim result As String = ""
result = testString.Substring(testString.LastIndexOf(",") + 1)
Note the +1 to move to the character after the comma. You should really also find the index first and add checks to confirm that the index is not -1 and index < testString.Length too.
Alternatives(I assume you want all the text after last comma):
Using LastIndexOf:
' You can add code to check if the LastIndexOf returns a positive number
Dim result As String = testString.SubString(testString.LastIndexOf(",")+1)
Regular Expressions:
Dim result As String = Regex.Replace(testString, "(.*,)(.*)$", "$2")
The third argument of indexOf is the number of charcters to search. You are searching for , starting at 0 for 3 characters - that is searching the string par for a comma which does not exist so the returned index is -1, hence your error. I think that you would need to use some recursion:
Dim testString As String = "part, description, order, get this text"
Dim index As Int32 = 0
For i As Int32 = 1 To 3
index = testString.IndexOf(","c, index + 1)
If index < 0 Then
' Not enough commas. Handle this.
End If
Next
Dim result As String = testString.Substring(index + 1)
The IndexOf function only finds the "First" of the specified character. The last parameter (in your case 3) specifies how many characters to examine and not the occurence.
Refer to Find Nth occurrence of a character in a string
The function specified here finds the Nth occurance of a character. Then use the substring function on the occurance returned.
Alternative , you can also use regular expression to find the nth occurance.
public static int NthIndexOf(this string target, string value, int n)
{
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}");
if (m.Success)
{
return m.Groups[2].Captures[n - 1].Index;
}
else
{
return -1;
}
}
I think this is what you are looking for
Dim testString As String = "part, description, order, get this text"
Dim resultArray As String() = testString.Split(New Char() {","c}, 3)
Dim resultString As String = resultArray(2)