Inserting a word within a given string - input

I want the user to input a phrase such as "Python" and have the program put the word "test" in the middle.... So it would print "pyttesthon".
After I input the phrase however, I am not sure which function to use.

You can just concatenate strings like so:
stringToInsert = "test"
oldString = "Python"
newString = oldString[0:len(oldString)/2] + stringToInsert + oldString[len(oldString)/2:]

Related

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

How To Remove Last Word With Slash In A Textbox VB.NET

I'm trying to remove the last word on a Label with it's slash without putting it in a String or an Array because the words are typed, looks something like this D:\Folder1\Folder2\Folder3\Folder4 and if i click a button it should remove the Folder4 and when i click the button again it should remove the Folder3 and so on.
Dim s As String = Label5.Text
Dim r As String = Replace(s, "\", "")
Label5.Text = r
And this only removes the slash, how do i add the texts?
I tried something like this:
Replace(s, "\" & Label5.Text.TrimEnd, "")
but nothing happens. Help?
The string class has a method called LastIndexOf that tells you the index of the last character that you pass as parameter.
Then the Substring method allows you to keep only the part before that index
' Label.Text = "D:\Folder1\Folder2\Folder3\Folder4"
Dim pos As Integer = Label.Text.LastIndexOf("\")
if pos <> -1 Then
Label.Text = Label.Text.Substring(0, pos)
End If
No need to split the input in an array and then rebuild your string.
Another method, very simple, (but that carries also an assumption) is to use the Path class
' Label.Text = "D:\Folder1\Folder2\Folder3\Folder4"
Label.Text = Path.GetDirectoryName(Label.Text)
The assumption, of course, is in the fact, that you have a correctly typed folder name (not necessary that the folder exists though)
Idea is, to find last word by splitting the string with \ and then finding last element in the splitted array
Dim s As String = Label5.Text '"D:\Folder1\Folder2\Folder3\Folder4"
Dim r As String = s.Replace("\" & s.Split("\")(s.Split("\").Length-1), String.Empty)
Label5.Text=r 'Console.Write(r)
Try this:
Dim r as String = Replace(s, s.Split("\").Last(), "")
.Last() will make sure you get the last word after the "\"

Sampling StringName.SubString(p,1) for paragraph formatting character

please try to specifically answer my question and not offer alternative approaches as I have a very specific problem that needs this ad-hoc solution. Thank you very much.
Automatically my code opens Word through VB.NET, opens the document, finds the table, goes to a cell, moves that cells.range.text into a String variable and in a For loop compares character at position p to a String.
I have tried Strings:
"^p", "^013", "U+00B6"
My code:
Dim nextString As String
'For each cell, extract the cell's text.
For p = 17 To word_Rng.Cells.Count
nextString = word_Rng.Cells(p).Range.Text
'For each text, search for structure.
For q = 0 To nextString.Length - 1
If (nextString.Substring(q, 1) = "U+00B6") Then
Exit For
End If
Next
Next
Is the structural data lost when assigning the cells text to a String variable. I have searched for formatting marks like this in VBA successfully in the past.
Assuming that your string contains the character, you can use ChrW to create the appropriate character from the hex value, and check for that:
If nextString.Substring(q, 1) = ChrW(&h00B6) Then
Exit For
End If
UPDATE
Here's a complete example:
Dim nextString = "This is a test " & ChrW(&H00B6) & " for that char"
Console.WriteLine(nextString)
For q = 0 To nextString.Length - 1
If nextString(q) = ChrW(&H00B6) Then
Console.WriteLine("Found it: {0}", q)
End If
Next
This outputs:
This is a test ¶ for that char
Found it: 15

Getting one word from given string

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.

How to find which delimiter was used during string split (VB.NET)

lets say I have a string that I want to split based on several characters, like ".", "!", and "?". How do I figure out which one of those characters split my string so I can add that same character back on to the end of the split segments in question?
Dim linePunctuation as Integer = 0
Dim myString As String = "some text. with punctuation! in it?"
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "." Then linePunctuation += 1
Next
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "!" Then linePunctuation += 1
Next
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "?" Then linePunctuation += 1
Next
Dim delimiters(3) As Char
delimiters(0) = "."
delimiters(1) = "!"
delimiters(2) = "?"
currentLineSplit = myString.Split(delimiters)
Dim sentenceArray(linePunctuation) As String
Dim count As Integer = 0
While linePunctuation > 0
sentenceArray(count) = currentLineSplit(count)'Here I want to add what ever delimiter was used to make the split back onto the string before it is stored in the array.'
count += 1
linePunctuation -= 1
End While
If you add a capturing group to your regex like this:
SplitArray = Regex.Split(myString, "([.?!])")
Then the returned array contains both the text between the punctuation, and separate elements for each punctuation character. The Split() function in .NET includes text matched by capturing groups in the returned array. If your regex has several capturing groups, all their matches are included in the array.
This splits your sample into:
some text
.
with punctuation
!
in it
?
You can then iterate over the array to get your "sentences" and your punctuation.
.Split() does not provide this information.
You will need to use a regular expression to accomplish what you are after, which I infer as the desire to split an English-ish paragraph into sentences by splitting on punctuation.
The simplest implementation would look like this.
var input = "some text. with punctuation! in it?";
string[] sentences = Regex.Split(input, #"\b(?<sentence>.*?[\.!?](?:\s|$))");
foreach (string sentence in sentences)
{
Console.WriteLine(sentence);
}
Results
some text.
with punctuation!
in it?
But you are going to find very quickly that language, as spoken/written by humans, does not follow simple rules most of the time.
Here it is in VB.NET for you:
Dim sentences As String() = Regex.Split(line, "\b(?<sentence>.*?[\.!?](?:\s|$))")
Once you've called Split with all 3 characters, you've tossed that information away. You could do what you're trying to do by splitting yourself or by splitting on one punctuation mark at a time.