How To Remove Last Word With Slash In A Textbox VB.NET - 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 "\"

Related

VB.NET - Delete excess white spaces between words in a sentence

I'm a programing student, so I've started with vb.net as my first language and I need some help.
I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.
I made a part of the code but it doesn't work, Thanks.
enter image description here
Knocked up a quick routine for you.
Public Function RemoveMyExcessSpaces(str As String) As String
Dim r As String = ""
If str IsNot Nothing AndAlso Len(str) > 0 Then
Dim spacefound As Boolean = False
For i As Integer = 1 To Len(str)
If Mid(str, i, 1) = " " Then
If Not spacefound Then
spacefound = True
End If
Else
If spacefound Then
spacefound = False
r += " "
End If
r += Mid(str, i, 1)
End If
Next
End If
Return r
End Function
I think it meets your criteria.
Hope that helps.
Unless using those VB6 methods is a requirement, here's a one-line solution:
TextBox2.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
Online test: http://ideone.com/gBbi55
String.Split() splits a string on a specific character or substring (in this case a space) and creates an array of the string parts in-between. I.e: "Hello There" -> {"Hello", "There"}
StringSplitOptions.RemoveEmptyEntries removes any empty strings from the resulting split array. Double spaces will create empty strings when split, thus you'll get rid of them using this option.
String.Join() will create a string from an array and separate each array entry with the specified string (in this case a single space).
There is a very simple answer to this question, there is a string method that allows you to remove those "White Spaces" within a string.
Dim text_with_white_spaces as string = "Hey There!"
Dim text_without_white_spaces as string = text_with_white_spaces.Replace(" ", "")
'text_without_white_spaces should be equal to "HeyThere!"
Hope it helped!

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

Replacing string at certain index of Split

Using streamreader to read line by line of a text file. When I get to a certain line (i.e., 123|abc|99999||ded||789), I want to replace ONLY the first empty area with text.
So far, I've been toying with
If sLine.Split("|")(3) = "" Then
'This is where I'm stuck, I want to replace that index with mmm
End If
I want the output to look like this: 123|abc|99999|mmm|ded||789
Considering you already have code determining if the "mmm" string needs to be added or not, you could use the following:
Dim index As Integer = sLine.IndexOf("||")
sLine = sLine.Insert(index + 1, "mmm")
You could split the string, modify the array and rejoin it to recreate the string:
Dim sLine = "123|abc|99999||ded||789"
Dim parts = sLine.Split("|")
If parts(3) = "" Then
parts(3) = "mmm"
sLine = String.Join("|", parts)
End If
I gather that if you find one or more empty elements, you want to replace the first empty element with data and leave the rest blank. You can accomplish this by splitting on the pipe to get an array of strings, iterate through the array and replace the first empty element you come across and exit the loop, and then rejoin your array.
Sub Main()
Dim data As String = "123||abc|99999||ded||789"
Dim parts = data.Split("|")
For index = 0 To parts.Length - 1
If String.IsNullOrEmpty(parts(index)) Then
parts(index) = "mmm"
Exit For
End If
Next
data = String.Join("|", parts)
Console.WriteLine(data)
End Sub
Results:
123|mmm|abc|99999||ded||789

search for filenames in textfiles

I have a powershell script that pulls out lines containing ".html" ".css" and so forth
however what I need is to be able to strip out the entire filename
using a pattern.... the entire pattern is returned example
.........\.html returns
src="blank.html"
my answer came in VB (with a bunch of work and even more research) I wanted to share with you all the results, it's not pretty but it works. is there an easier way?
I have commented the code to help in understanding.
Private Sub find()
Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(openWork.FileName)
Dim a As String
Dim SearchForThis As String
Dim allfilenames As New System.Text.StringBuilder
Dim first1 As String
Dim FirstCharacter As Integer
'Dim lines As Integer
SearchForThis = txtFind.Text
Do
a = reader.ReadLine 'reader.Readling
If a = "" Then
a = reader.ReadLine
End If
If a Is Nothing Then 'without this check the for loops run with bad data, but I can't check "a" without reading it first.
Else
For FirstCharacter = 2 To a.Length - SearchForThis.Length ' start at 2 to prevent errors in the ")" check
If Mid(a, FirstCharacter, SearchForThis.Length) = SearchForThis Then ' compare the line character by character to find the searchstring
If Mid(a, FirstCharacter - 1, 1) <> ")" Then ' checks for ")" just before the searchstring (a common problem with my .CSS finds)
For y = FirstCharacter To 1 Step -1
If Mid(a, y, 1) = Mid(a, FirstCharacter + SearchForThis.Length, 1) Then ' compares the character after searchstring till I find another one
Dim temp = Mid(a, y + 1, (FirstCharacter + SearchForThis.Length) - 1 - y) ' puts the entire filename into variable "temp"
allfilenames.Append(temp & Chr(13)) 'adds the contents of temp (and a carrage return) to the allfilenames stringbuilder
y = 1
Else
End If
Next
End If
End If
Next
End If
Loop Until a Is Nothing
Document.Text = allfilenames.ToString
reader.Close()
End Sub
(updating for comments... thanks for the input)
each line in the .css search file looks something like this.
addPbrDlg.html:12:<link rel=stylesheet href="swl_styles-5.0o-97581885.css" TYPE="text/css">
addPbrDlg.html:727: html(getFrame(statusFrame).strErrorMessage).css('color','red');
for this I want to return
swl_styles-5.0o-97581885.css
but not return
statusFrame).strErrorMessage).css
basically I want to strip out the file names from HTML code
but if I use a pattern like
.............................\.css
it would return something like
t href="swl_styles-5.0o-97581885.css
Finally... there are some variables that I don't need to worry about (due to my personal situation) like I know that all web pages are ".html" all images are ".gif" there are ".css" and ".js" files as well that I want to pull. But because the designers are extremely consistant I know that there aren't any surprise files (.jpg or .htm)
I can also assume that if there is a single quote after the filename, there will be a single quote before. same with double quote.
Thanks for your input so far... I appreciate your time and knowledge.
You need to use Regex and do something like this
Dim files = Regex.Matches("<your whole file text>", "Your regex pattern");
Your regex pattern will look something like this "\Asrc="".+((\.html)|(\.css))"")". This is probably wrong but when you get that straight follow with
Dim fileList as new List(of String)
For Each file as Match in files
' strip " src=" " and last " " "
fileList.Add(file.Value.Substring(5, file.Value.Length - 6))
Next

How do I manipulate the last string of a Richtextbox in Visual Basic

I am trying to take a string in a rich text box and replace them with a different string.
Now how this should work is that if two same characters are entered into the text box
e.g tt the "tt" will be replaced with "Ǿt" , it adds back one of the t's to the replaced string. Only the most recently entered string is manipulated if two same characters are entered .
I read the LAST string that is in the RichTextBox by using this method
Dim laststring As String = RichTextBox1.Text.Split(" ").Last
'hitting space bar breaks the operation so if i enter t t there will be no replacement
this is the replacement method which I use , it works correctly .
if laststring = "tt"
RichTextBox1 .Text = RichTextBox1 .Text.Replace("tt", "Ǿt")
This method is inefficient because i need to check id there are double letters for all letters and if i was to use this method it would tavke up a lot of code .
how can I accomplish this using a shorter method??
You need to put the if then section in a loop.
Dim holdstring As String
Dim doubleinstance() As String = {"bb", "tt", "uu"} ' array
Dim curstring As String = RichTextBox1.Text.Split(" ").Last
For Each item As String In doubleinstance
If RichTextBox1.Text.EndsWith(item) Then
holdstring = RichTextBox1.Text.Split(" ").Last.Length - 1 ' change to subtract 1 character from doubleinstance
RichTextBox1.Text = RichTextBox1.Text.Replace(curstring, "Ǿt" & holdstring)
MsgBox(curstring)
End If
Next item
Here's a bit of code to get you in the right direction...
There are a couple of variations of .Find, but you probably want to look at the .Select method.
With RichTextBox1
.Find("Don")
.SelectedText = "Mr. Awesome"
End With
Here is a way I came up with
Dim holdstring As String
Dim doubleinstance() As String = {"bb", "tt", "uu"} ' array
Dim curstring As String = RichTextBox1.Text.Split(" ").Last
If curstring = doubleinstance(0) And RichTextBox1.Text.EndsWith(doubleinstance(0)) Then
holdstring = RichTextBox1.Text.Split(" ").Last.Length - 1 ' change to subtract 1 character from doubleinstance
RichTextBox1.Text = RichTextBox1.Text.Replace(curstring, "Ǿt" + holdstring)
MsgBox(curstring)
End If
where i have doubleinstance(0) how do i get the if statement to not only check a single index but all of the index from 0 to 2 in this example ?