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
Related
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
I'm looking for a way in VB to find a string between two characters,
"(" and ")".
For example, for the string...
"THIS IS (ONE) AND THIS IS (TWO)"
....I would like for a variable to store the characters between the
second set of parenthesis, e.g.
strMyString = "TWO".
But if the string to search only contains one set of parenthesis, to
store this instead. e.g.
strFirstString = "THIS IS (ONE)"
strMyString = "ONE"
As a preliminary answer, you can use this function to find the string within the last pair or brackets in your test string. If the brackets are in the wrong order or if brackets are missing it will throw an exception.
Private Function StringInLastBracketPair(testString As String) As String
Dim startBracket, endBracket As Integer
startBracket = testString.LastIndexOf("(") + 1
endBracket = testString.LastIndexOf(")")
If startBracket >= endBracket Or startBracket = 0 Or endBracket = -1 Then
Throw New System.Exception("String is not formatted properly : " & testString)
End If
StringInLastBracketPair = stringToTest.Substring(startBracket, endBracket - startBracket)
End Function
I have the following strings: Anaheim Temp. 1-N/A and Cevera-N/A.
How do I get Temp from the first one and Cevera from the second one?
So sorry,I'll try to provide more info: So lets say I want to split the first string to first name and last name so first name would be "Anaheim" last name would be "Temp" second example: "Alex Orellana-NA" so first name would be "Alex" last name "Orellana" how do I get rid of whats coming after special characters like "-" "." "/"
I think I understand what you are asking for. You are looking for a function that will take 2 strings and search one string with a phrase, then return the result if it contains it. I believe I have a solution to your issue:
Public Function FindCertainString(stringToSearch As String, stringToFind As String) As String
For index = 1 To stringToSearch.Length - 1
Dim character As Char = stringToSearch(index)
' Parse through whole string and find any match values
If character = stringToFind(0) Then
' Matched the first letter
Dim tempIndex As Integer = index
Dim someWord As String = ""
For innerIndex = 1 To stringToFind.Length
someWord += stringToSearch(tempIndex)
tempIndex += 1
Next
If someWord = stringToFind Then
' Found the word you were looking for
Return someWord
End If
End If
Next
Return ""
End Function
This should satisfy what you are looking for because what this function will do is take in the two strings then for the stringToSearch it will prase through each character until it identifies a match to the beginning letter in the stringToFind from there it collects together an equal length in characters and examines if it matches the stringToFind value.
Info : This answer is obsolete and was based on the initial question of OP before the Edits.
"Anaheim Temp. 1-N/A".IndexOf("Temp") ' -> returns 8 = found at index 8 !
"Cevera-N/A".IndexOf("Cevera") ' -> returns 0 = found at index 0 !
"Cevera-N/A".IndexOf("Temp") ' -> returns -1 = not found !
"Cevera-N/A".IndexOf("cevera") ' -> returns -1 = not found ! because it's lowercase !
I do agree with the comments above : you didn't provide what's the purpose of finding the specified word, or wether are your looking for a complex logic to confirm the presence of a specific identifer in a literal (Temp or Cereva or any other specific word in ANY provided literal sentence or formula)
We don't know what's the meaning of "Anaheim Temp. 1-N/A", where did that came from, wether it's the value of a string variable or some literal expression of a formula entered in a text box...
You want to find "Temp" in "Anaheim Temp. 1-N/A", it's there already !!! How on earth would we have to search far away, while obviously "Anaheim Temp. 1-N/A" contains "Temp" ?
And there are several ways to know if a String contains another String, but the usefull one depends on where the string "Anaheim Temp. 1-N/A" came from and why the string "Temp" should be found there but not "1" or "-N" or even "SantaMaria", and the purpose of searching that word for...
You haven't tried anything so far if I understand, while you want us to guess the logic behind.. XD
What the following code does is to extract Name components one by one until an invalid character is found.
The Function input is a String which holds the literal names.
The output is a List(Of String) that contains each extracted name component.
Sample test -> Resulting Name Components
"Anaheim Temp. 1-N/A" -> [Anaheim],[Temp]
"Cevera-N/A" -> [Cevera]
"Alex Orellana-NA" -> [Alex],[Orellana]
"Marie J Blige ?" -> [Marie],[J],[Blige]
"Marie J. Blige /vv" -> [Marie],[J.],[Blige]
"José F. 1452" -> [José],[F.]
"P. P. d'Arvor" -> [P.],[P.],[d]
To make "P. P. d'Arvor" work, should include handling of ['] char, which I didn't.
(EDIT : It wasn't about Substrings.)
Public Function GetNames(ByVal SampleName As String) As List(Of String)
Dim CharIndex As Integer = 0
Dim NameStart As Integer = 0
Dim NamesList As New List(Of String)
' Iterate the Chars from the left
While CharIndex < SampleName.Length
If Not Char.IsLetter(SampleName(CharIndex)) Then
If Char.IsWhiteSpace(SampleName(CharIndex)) Then
If CharIndex > NameStart Then
NamesList.Add(SampleName.Substring(NameStart, CharIndex - NameStart))
End If
NameStart = CharIndex + 1
Else
If (SampleName(CharIndex) = "."c) Then
' This, to allow examples like "Angelina J.-N/A"
' "Angelina" will be added first
' then "J." (with the dot) will be added aswell.
If NameStart = (CharIndex - 1) Then
' This simple check prevent the picking of
' two consecutive dots like
' "Jarod R.. Solo" -> "Jarod" and "R." ("Solo" discarded)
' "A. Leo D........" -> "A.", "Leo" and "D."
' ". Andrew" -> "" (break immediately)
NamesList.Add(SampleName.Substring(NameStart, CharIndex - NameStart + 1))
NameStart = CharIndex + 1
Else
If NameStart < CharIndex Then
NamesList.Add(SampleName.Substring(NameStart, CharIndex - NameStart))
End If
Exit While
End If
Else
If NameStart < CharIndex Then
NamesList.Add(SampleName.Substring(NameStart, CharIndex - NameStart))
End If
Exit While ' Discard the rest
End If
End If
End If
CharIndex = CharIndex + 1
End While
Return NamesList
End Function
Then use a Method like this :
Public Sub TestNames()
Dim TestName As String
Dim NameComponents As List(Of String)
TestName = Microsoft.VisualBasic.InputBox("Enter Name") ' lazy me -_-
NameComponents = GetNames(TestName)
' wanna see preview ? un-comment the following.
'TestName = ""
'For Each Word As String In NameComponents
' TestName = TestName + "[" + Word + "]" + Environment.NewLine
'Next
'MessageBox.Show(TestName)
If NameComponents.Count > 1 Then ' You have at least two Names.
' The logic here is up to you
' FirstName = NameComponent.Item(0)
' LastName = NameComponent.Item(1)
ElseIf NameComponents.Count > 0 Then ' You have only one Name.
' FirstName = NameComponent.Item(0)
' LastName = ""
Else
' FirstName = "Unknown"
' LastName = ""
End If
End Sub
EDIT : Fixed the multiple consecutive dots syndrome.
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
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)