Visual Basic Replace is not working - vb.net

I am writing a simple hangman program and I want to replace something in my variable which stores the letters of the word that have been found.
Here is the code:
Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter)
wordLettersFound, counter and letter are 3 of the variables I am using.
The variable is all underscores before this script, but it does not change! Can anyone help me with this?
P.S.
I do not know what version of VB I am using, visual studio community 2015 just says 'visual basic'.

Replace doesn't modify the string but returns a new string with the replacement so you should assign it to the variable:
wordLettersFound = Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter)

Another way to do replace,
Dim theLetters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzAAA"
theLetters = theLetters.Replace("A"c, "#"c)

There is another way to replace a character in a string. Using the Replace function is a bit awkward in your case because, at the start, all the characters are underscores - Replace as you're using it will replace all of them with the found character.
Instead, you can cut up the string to the piece to the left of the desired replacement, add in the replacement character, and add on the rest of the string. That line is the one after the comment "chop foundWord up and put the character in the right place" in this code:
Module Module1
Sub Main()
Dim wordToFind = "alphabet"
' make a string of dashes the same length as the word to find
Dim foundWord = New String("-"c, wordToFind.Length)
While foundWord <> wordToFind
Console.Write("Enter your guess for a letter: ")
Dim guess = Console.ReadLine()
' make sure the user has only entered one character
If guess.Length = 1 Then
' see if the letter is in the string
Dim pos = wordToFind.IndexOf(guess)
While pos >= 0
' chop foundWord up and put the character in the right place
foundWord = foundWord.Substring(0, pos) & guess & foundWord.Substring(pos + 1)
' see if there are any more of the same letter
pos = wordToFind.IndexOf(guess, pos + 1)
End While
' show the user the current progress
Console.WriteLine(foundWord)
Else
Console.WriteLine("Please enter just one letter!")
End If
End While
Console.WriteLine("You did it!")
Console.WriteLine("Press enter to leave the program.")
Console.ReadLine()
End Sub
End Module
N.B. Do not use all that code directly for homework because your teacher will find this. And that goes to anyone else doing homework - you know who you are ;)

Related

When I run the code, get the results and repeat, the previous user input displays right before the new user input. Any idea?

Can anyone help steer me into the right direction?
I am trying to separate the string into characters. If the character is lowercase then the program will uppercase it and vice versa.
Module Module1
Sub Main()
Dim Input As String
Dim Output As New Text.StringBuilder()
Dim repeat As String = "Y"
Do While repeat = "Y"
Console.Clear()
Console.WriteLine("Please enter a word or" &
"phrase and I will change upper case to lower case and vice versa")
Input = Console.ReadLine
For Each ch As Char In Input
If Char.IsLower(ch) Then
Output.Append(Char.ToUpper(ch))
ElseIf Char.IsUpper(ch) Then
Output.Append(Char.ToLower(ch))
Else
Output.Append(ch)
End If
Next
Console.WriteLine(Output.ToString())
Console.Write("Lets try another (Y/N) ")
repeat = UCase(Console.ReadLine())
Loop
Console.ReadKey()
End Sub
End Module
Think about what you're doing with Output; you keep appending to it, but never remove the results from the previous loop from it, so it's gonna display it again and again.
So to fix your problem you need to make sure output is emptied before adding new characters to it. I don't really work with stringbuilders but a simple way would be to just do
Output = New Text.StringBuilder()
at the beginning of your loop

Excel VBA Using wildcard to replace string within string

I have a difficult situation and so far no luck in finding a solution.
My VBA collects number figures like $80,000.50. and I'm trying to get VBA to remove the last period to make it look like $80,000.50 but without using right().
The problem is after the last period there are hidden spaces or characters which will be a whole lot of new issue to handle so I'm just looking for something like:
replace("$80,000.50.",".**.",".**")
Is this possible in VBA?
I cant leave a comment so....
what about InStrRev?
Private Sub this()
Dim this As String
this = "$80,000.50."
this = Left(this, InStrRev(this, ".") - 1)
Debug.Print ; this
End Sub
Mid + Find
You can use Mid and Find functions. Like so:
The Find will find the first dot . character. If all the values you are collecting are currency with 2 decimals, stored as text, this will work well.
The formula is: =MID(A2,1,FIND(".",A2)+2)
VBA solution
Function getStringToFirstOccurence(inputUser As String, FindWhat As String) As String
getStringToFirstOccurence = Mid(inputUser, 1, WorksheetFunction.Find(FindWhat, inputUser) + 2)
End Function
Other possible solutions, hints
Trim + Clear + Substitute(Char(160)): Chandoo -
Untrimmable Spaces – Excel Formula
Ultimately, you can implement Regular expressions into Excel UDF: VBScript’s Regular Expression Support
How about:
Sub dural()
Dim r As Range
For Each r In Selection
s = r.Text
l = Len(s)
For i = l To 1 Step -1
If Mid(s, i, 1) = "." Then
r.Value = Mid(s, 1, i - 1) & Mid(s, i + 1)
Exit For
End If
Next i
Next r
End Sub
This will remove the last period and leave all the other characters intact. Before:
and after:
EDIT#1:
This version does not require looping over the characters in the cell:
Sub qwerty()
Dim r As Range
For Each r In Selection
If InStr(r.Value, ".") > 0 Then r.Characters(InStrRev(r.Text, "."), 1).Delete
Next r
End Sub
Shortest Solution
Simply use the Val command. I assume this is meant to be a numerical figure anyway? Get rid of commas and the dollar sign, then convert to value, which will ignore the second point and any other trailing characters! Robustness not tested, but seems to work...
Dim myString as String
myString = "$80,000.50. junk characters "
' Remove commas and dollar signs, then convert to value.
Dim myVal as Double
myVal = Val(Replace(Replace(myString,"$",""),",",""))
' >> myVal = 80000.5
' If you're really set on getting a formatted string back, use Format:
myString = Format(myVal, "$000,000.00")
' >> myString = $80,000.50
From the Documentation,
The Val function stops reading the string at the first character it can't recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized.
This is why we must first remove the dollar sign, and why it ignores all the junk after the second dot, or for that matter anything non numerical at the end!
Working with Strings
Edit: I wrote this solution first but now think the above method is more comprehensive and shorter - left here for completeness.
Trim() removes whitespace at the end of a string. Then you could simply use Left() to get rid of the last point...
' String with trailing spaces and a final dot
Dim myString as String
myString = "$80,000.50. "
' Get rid of whitespace at end
myString = Trim(myString)
' Might as well check if there is a final dot before removing it
If Right(myString, 1) = "." Then
myString = Left(myString, Len(myString) - 1)
End If
' >> myString = "$80,000.50"

VBA Find function incorrect highlighting

Can somebody help me fix this code, I have two textbox where when you paste the text on the 1st Textbox and click the search button, it highlighted the exact text on the 2nd textbox if it is present on the 2nd textbox. But when the string on 2nd textbox contains linefeed/newline, it added one character from the start of the text. Here is the code:
Private Sub FindText(ByVal start_at As Integer)
Dim pos As Integer
Dim target As String
target = Textbox1.Text
pos = InStr(start_at, Textbox2.Text, target)
If pos > 0 Then
' We found it.
TargetPosition = pos
Textbox2.SelStart = TargetPosition - 1
Textbox2.SelLength = Len(target)
Textbox2.SetFocus
Else
' We did not find it.
MsgBox "Not found."
Textbox2.SetFocus
End If
End Sub
' Search button
Private Sub cmdSearch_Click()
FindText 1
End Sub
I believe the problem is that Textbox is treating newline as a single character while Len() counts as CRLF as two. You should probably count the number of times CRLF appears in the text preceding the match target and adjust SelStart accordingly. Try this line instead:
Textbox2.SelStart = Len(Replace(Left(target, pos - 1), vbCrLf, "^")) - 1
'Textbox2.SelLength = Len(Replace(target, vbCrLf, "^"))
If target can include line breaks you may have a similar problem with SelLength which is why I've left the second, commented line. This works by substituting two-character line-break sequences into a single-character string. It's completely arbitrary what value to use for replacement since the result is discarded and only the length ultimately matters.

How does the Val() function in VB.NET work?

I have an assignment in VB.NET that I'm stuck with at the moment. Would love some help.
The question is this: You enter random characters into a textbox, for example 12ab3c4d5efgh, and at the click of a button, it must sort the characters in the textbox into 2 separate Labels, depending on whether or not the 'character' is a number or letter. So, continuing the example, Label1 must show '12345' and Label 2 must show 'abcdefgh'. I hope I made myself clear enough.
I was asked to use the Val() function but I really have no clue. Could someone please help? :D
This creates one string with the digits and one with the letters. Characters that are not digits or letters are ignored.
Dim chars As String = "12ab3c4d5efgh"
Dim nums As String = chars.Where(Function(c) Char.IsDigit(c)).ToArray
Dim lets As String = chars.Where(Function(c) Char.IsLetter(c)).ToArray
If you have to use Val() something like this would do. But be careful: Val("0") also returns 0.
Dim numbers As String = String.Empty
Dim letters As String = String.Empty
Dim sourceString As String = "12ab3c4d50efgh"
For Each c As Char In sourceString
If Val(c) = 0 And c <> "0" Then letters &= c Else numbers &= c
Next
Console.WriteLine("Numbers: " & numbers)
Console.WriteLine("Letters: " & letters)
Console.ReadKey()

How to normalize filenames listed in a range

I have a list of filenames in a spreadsheet in the form of "Smith, J. 010112.pdf". However, they're in the varying formats of "010112.pdf", "01.01.12.pdf", and "1.01.2012.pdf". How could I change these to one format of "010112.pdf"?
Personally I hate using VBA where worksheet functions will work, so I've worked out a way to do this with worksheet functions. Although you could cram this all into one cell, I've broken it out into a lot of independent steps in separate columns so you can see how it's working, step by step.
For simplicity I'm assuming your file name is in A1
B1 =LEN(A1)
determine the length of the filename
C1 =SUBSTITUTE(A1," ","")
replace spaces with nothing
D1 =LEN(C1)
see how long the string is if you replace spaces with nothing
E1 =B1-D1
determine how many spaces there are
F1 =SUBSTITUTE(A1," ",CHAR(8),E1)
replace the last space with a special character that can't occur in a file name
G1 =SEARCH(CHAR(8), F1)
find the special character. Now we know where the last space is
H1 =LEFT(A1,G1-1)
peel off everything before the last space
I1 =MID(A1,G1+1,255)
peel off everything after the last space
J1 =FIND(".",I1)
find the first dot
K1 =FIND(".",I1,J1+1)
find the second dot
L1 =FIND(".",I1,K1+1)
find the third dot
M1 =MID(I1,1,J1-1)
find the first number
N1 =MID(I1,J1+1,K1-J1-1)
find the second number
O1 =MID(I1,K1+1,L1-K1-1)
find the third number
P1 =TEXT(M1,"00")
pad the first number
Q1 =TEXT(N1,"00")
pad the second number
R1 =TEXT(O1,"00")
pad the third number
S1 =IF(ISERR(K1),M1,P1&Q1&R1)
put the numbers together
T1 =H1&" "&S1&".pdf"
put it all together
It's kind of a mess because Excel hasn't added a single new string manipulation function in over 20 years, so things that should be easy (like "find last space") require severe trickery.
Here's a screenshot of a simple four-step method based on Excel commands and formulas, as suggested in a comment to the answered post (with a few changes)...
This function below works. I've assumed that the date is in ddmmyy format, but adjust as appropriate if it's mmddyy -- I can't tell from your example.
Function FormatThis(str As String) As String
Dim strDate As String
Dim iDateStart As Long
Dim iDateEnd As Long
Dim temp As Variant
' Pick out the date part
iDateStart = GetFirstNumPosition(str, False)
iDateEnd = GetFirstNumPosition(str, True)
strDate = Mid(str, iDateStart, iDateEnd - iDateStart + 1)
If InStr(strDate, ".") <> 0 Then
' Deal with the dot delimiters in the date
temp = Split(strDate, ".")
strDate = Format(DateSerial( _
CInt(temp(2)), CInt(temp(1)), CInt(temp(0))), "ddmmyy")
Else
' No dot delimiters... assume date is already formatted as ddmmyy
' Do nothing
End If
' Piece it together
FormatThis = Left(str, iDateStart - 1) _
& strDate & Right(str, Len(str) - iDateEnd)
End Function
This uses the following helper function:
Function GetFirstNumPosition(str As String, startFromRight As Boolean) As Long
Dim i As Long
Dim startIndex As Long
Dim endIndex As Long
Dim indexStep As Integer
If startFromRight Then
startIndex = Len(str)
endIndex = 1
indexStep = -1
Else
startIndex = 1
endIndex = Len(str)
indexStep = 1
End If
For i = startIndex To endIndex Step indexStep
If Mid(str, i, 1) Like "[0-9]" Then
GetFirstNumPosition = i
Exit For
End If
Next i
End Function
To test:
Sub tester()
MsgBox FormatThis("Smith, J. 01.03.12.pdf")
MsgBox FormatThis("Smith, J. 010312.pdf")
MsgBox FormatThis("Smith, J. 1.03.12.pdf")
MsgBox FormatThis("Smith, J. 1.3.12.pdf")
End Sub
They all return "Smith, J. 010312.pdf".
You don't need VBA. Start by replacing the "."s with nothing:
=SUBSTITUTE(A1,".","")
This will change the ".PDF" to "PDF", so let's put that back:
=SUBSTITUTE(SUBSTITUTE(A1,".",""),"pdf",".pdf")
Got awk? Get the data into a text file, and
awk -F'.' '{ if(/[0-9]+\.[0-9]+\.[0-9]+/) printf("%s., %02d%02d%02d.pdf\n", $1, $2, $3, length($4) > 2 ? substr($4,3,2) : $4); else print $0; }' your_text_file
Assuming the data are exactly as what you described, e.g.,
Smith, J. 010112.pdf
Mit, H. 01.02.12.pdf
Excel, M. 8.1.1989.pdf
Lec, X. 06.28.2012.pdf
DISCLAIMER:
As #Jean-FrançoisCorbett has mentioned, this does not work for "Smith, J. 1.01.12.pdf". Instead of reworking this completely, I'd recommend his solution!
Option Explicit
Function ExtractNumerals(Original As String) As String
'Pass everything up to and including ".pdf", then concatenate the result of this function with ".pdf".
'This will not return the ".pdf" if passed, which is generally not my ideal solution, but it's a simpler form that still should get the job done.
'If you have varying extensions, then look at the code of the test sub as a guide for how to compensate for the truncation this function creates.
Dim i As Integer
Dim bFoundFirstNum As Boolean
For i = 1 To Len(Original)
If IsNumeric(Mid(Original, i, 1)) Then
bFoundFirstNum = True
ExtractNumerals = ExtractNumerals & Mid(Original, i, 1)
ElseIf Not bFoundFirstNum Then
ExtractNumerals = ExtractNumerals & Mid(Original, i, 1)
End If
Next i
End Function
I used this as a testcase, which does not correctly cover all your examples:
Sub test()
MsgBox ExtractNumerals("Smith, J. 010112.pdf") & ".pdf"
End Sub