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()
Related
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!
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 ;)
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 ?
I'm learning vb.net. I'm trying to create an incremental number that starts at 00000 and concatenate that number with a value from a textbox (eg. JH00001), then insert it into the database.
Please can someone kindly help me with this as I'm totaly new to vb.net.
Thank you all for your assistance in advance. And I'm sorry for my bad English.
Dim number as Integer = 1
Dim text as String = textbox1.text &= number.toString().padLeft(5, "0"c)
Use D5 precision specifier to indicate that the number should be at least 5 digits including leading zeros:
Dim valueFromTextBox As String = "JH"
Dim value As String = ""
For i = 0 To 99
value = valueFromTextBox & i.ToString("D5")
'Insert value to database
Next
Check MSDN for more formatting methods
A for loop should be what you need:
Something like:
Dim text As String = textbox1.text
Dim DBtext As String
For value As Integer = 0 To 5
DBtext = text & value.ToString()
'Insert anything else you need to do. Such as insert into DB.
Next
Just replace the 5 with however many times you need it to run.
I personally prefer using String.Format ...
For i = 0 to 1e6-1
Dim FormattedString = String.Format("{0}{1:00000}", Textbox1.Text, i)
Next
I want to display the first and last characters of any given string entered into a textbox. The strings can be of any length as the user wants (as long as it is one word) I would like to be able to do something like this... "william = will and iam" or "Celtic = Cel and tic"
I understand I would have to split or divide the string. How would I go about doing this? Any help is appreciated, thanks.
EDIT:
Thanks for your help once again guys, this is how the code ended up!
Dim strInput = txtString.Text
Dim halflength = strInput.Length / 2
Dim firsthalf = strInput.Substring(0, halflength)
Dim secondhalf = strInput.Substring(halflength)
Dim strResults = firsthalf
Dim secondResult = secondhalf
MessageBox.Show(firsthalf)
MessageBox.Show(secondhalf)
MessageBox.Show("First half of string contains... " & " " & strResults.Length.ToString & " characters", "Character Count")
MessageBox.Show("Second half of string contains... " & " " & secondResult.Length.ToString & " characters", "Character Count")
EDIT:
Also meant to mention my current incorrect code.
Dim strInput As String
Dim strLength As String
Dim strResults As String
strInput = txtString.Text
strLength = strInput.Length / 2
strResults = txtString.Text
MessageBox.Show(strInput.Length.ToString, "Length of characters")
MessageBox.Show(strLength.ToString)
MessageBox.Show(strResults.Substring(0, 3))
String.Substring and String.Length should give you everything you need to get started on this.
Seeing your existing code will make this easier. Let's walk through what we have now.
Let's assume we have just a plain, simple string like this instead of a textbox for the sake of making things easier:
Dim txtString = "Hello World"
Now, in order to split the length of the string in half; we need to get the length. The `Length property will give is that, and then divide it by two.
Dim halfLength = txtString.Length \ 2
This will perform integer division; so any remaining decimal is truncated.
Now we know where the middle of the string is. We can now use String.Substring to carve out a peice of the string by index. Substring takes two parameters, the index where to start the string, and number of characters to take. There is a second overload that takes the index to start at and consumes till the end of the string. Indexes are zero based. So for example, if we wanted to start at the beginning of the string, we'd use zero. If we wanted to skip the first character, we'd use one.
For the first half of the string, we don't want to skip any characters, so we'll use zero. The number of characters we want is half length of the string, so we pass in halfLength:
Dim firstHalf = txtString.Substring(0, halfLength)
For the second half, we want to start in the middle of the string, and consume characters till the end, so we'll use the other overload:
Dim secondHalf = txtString.Substring(halfLength)
You now have your string split in half.
The final result looks like this:
Dim txtString = "Hello World"
Dim halfLength = txtString.Length \ 2
Dim firstHalf = txtString.Substring(0, halfLength)
Dim secondHalf = txtString.Substring(halfLength)
Assuming the rules are "each side is half the length with the left side taking precedence", you would use Substring and some simple division:
Dim str As String = "william"
Dim part1 As String = str.Substring(0, CInt(Math.Ceiling(str.Length / 2.0#)))
Dim part2 As String = str.Substring(part1.Length)
part1 & " and " & part2 'will and iam
Here's a demo.
My code displays first half and last half of any number of characters entered.
Declare Variable
Dim strResults As String
Fetch text from textbox
strResults = Textbox1.Text
Display the first half of the text
MessageBox.Show(strResults.Substring(0, strResults.Length / 2), "First Half Characters")
Display the last half of the text
MessageBox.Show(strResults.Substring(strResults.Length / 2), "Last Half Characters")
Full code:
Dim strResults As String
strResults = Textbox1.Text
MessageBox.Show(strResults.Substring(0, strResults.Length / 2), "First Half Characters")
MessageBox.Show(strResults.Substring(strResults.Length / 2), "Last Half Characters")