Visual Basic, Adding Values To Empty Char Array Elements - arrays

I'm having trouble filling up empty array elements in a char array.
I have an inputArray that will store all the characters that I type for myInput into an array. I then created a charArray that will take the characters from inputArray and then if it it comes across nothing in the array I want to add -1 to signal empty locations in my charArray. I haven't been able to do that. I type "Hello", it will output back to me
H
E
L
L
O
Space
Space
Space
Space
And So On, until I reach the end of that array.
*"Space" is for visual aid of output
I'm lost. I want to be able to filter out the "-1" and than count for the number of underscores I need to make up the word, like "Hello" would be _ _ _ _ _ (leaving out elements with "-1" or nothing inside of it.)
Module GuessingGame
Sub Main()
Dim myInput As String.
Dim inputArray(11) As Char
Dim charArray(11) As Char
Dim myLetter As String
Dim attempts As Integer = 0
Dim incorrectAttempts As Integer = 0
Dim remainingAttempts As Integer = 0
myInput = InputBox$("Please enter a word or phrase: ")
inputArray = myInput.ToCharArray()
While inputArray.Length > 12
System.Console.WriteLine("Error: The word or phrase needs to be 12 characters or less")
myInput = InputBox$("Please enter a word or phrase: ")
inputArray = myInput.ToCharArray()
End While
For i = 0 to inputArray.length - 1
If IsNothing(inputArray(i)) Then
charArray(i) = "-1"
Else
charArray(i) = inputArray(i)
End If
Next
Console.Clear()
For Each element In charArray
System.Console.WriteLine(element)
Next element
For i = 0 to inputArray.length - 1
remainingAttempts = remainingAttempts + 1
Next
remainingAttempts = remainingAttempts - 1
System.Console.WriteLine("Guessing Game Display")
System.Console.WriteLine("---------------------")
System.Console.WriteLine("Number of Remaining Attempts: " & remainingAttempts)
System.Console.WriteLine("Number of Incorrect Attempts: " & incorrectAttempts)
System.Console.WriteLine("Number of Attempts: " & attempts)
System.Console.WriteLine("Guess a Character? ")
myLetter = InputBox$("Please enter a character: ")
End Sub
End Module

I am not 100% but I am pretty sure the IsNothing is checking to see if there is a value at all.. Since you are automatically assigning the array to a size of 11 anything after the H E L L O is going to be set, but either "" or " " just an empty space. So try doing this
If inputArray(i) == "" Then
charArray(i) = "-1"
Else
charArray(i) = inputArray(i)
End If

I think your code work fine it must print -1 when there is space in integerArray. But on the code below u must modify it:
While inputArray.Length > 12
System.Console.WriteLine("Error: The word or phrase needs to be 12 characters or less")
myInput = InputBox$("Please enter a word or phrase: ")
'**/*it is better to remove these two code and replace it by goto above*/**
inputArray = myInput.ToCharArray()
End While

I was able to achieve what I wanted by first creating the char array, which would have the input of the word to guess. Then make string arrays, one that had the values from the char array and one that I would use for the guess array to compare off the first string array.
This was the work around to this problem.

Related

Properly Set Up Loop/ If Statements

I'm currently creating a program that will take user input.
If the user input contains _, then a variable substring will then equal the first 4 characters (0,4) of that input.
From there, a loop is run that loops through an array, and within that loop is an If statement that determines if the array contains the substring. And if so, the position of the array element that contains the substring is then equal to the same position of a different element array. And if any element from that array doesn't contain the substring, a MsgBox displays saying error.
Currently, if the user inputs text that in fact is a substring of that input is contained within the array, it is still prompting the error message, as well as displaying the correct outcome. How would I correctly set this up to where if the substring is not found within the array, the MsgBox will prompt the error, and if it is, only the correct outcome will be executed. Here's what I currently have:
And yes I know that both arrays don't contain the same amount of elements, I'm just testing the first three values.
Dim i As Integer
Dim subString As String
Dim IdValues = New String() {"ADC_123", "AAA_123", "AAB_123", "EFGH_Company", "ABB_456", "ABC_456"}
Dim ValueValues = New String() {"Happy", "Sad", "Mad", "Excited", "Joyful"}
Dim charText As Char
charText = "_"
If txtDataEntry.Text.Contains(charText) Then ' if statement to determine if text contains a "_"
subString = txtDataEntry.Text.Substring(0, 4) 'sets variable subString to a substring of text data
For i = 0 To IdValues.Length - 1 'looping through array
If IdValues(i).Contains(subString) And txtDataEntry.Text.Contains(IdValues(i)) Then
MsgBox("Success, the position is at position " & i)
IdValues(i) = ValueValues(i) 'new array position now equals the IdValue array where the substring is found
lblValueResult.Text = IdValues(i) 'prints outcome to label
Else
MsgBox("Error")
End If
Next i
Else
MsgBox("Sorry, no value was found.")
End If
So if the user enters AAA_123 it will create a substring AAA_ and determine if the IdValues array contains that substring. It is prompting the correct execution, but it is also prompting the Error message. How should I correctly set this up.
Any help is appreciated!
Using a Boolean for these types of iteration process is always better than playing around with if else .Please try the below answer
Dim isValueFound As Boolean = False
Dim i As Integer
Dim subString As String
Dim IdValues = New String() {"ADC_123", "AAA_123", "AAB_123", "EFGH_Company", "ABB_456", "ABC_456"}
Dim ValueValues = New String() {"Happy", "Sad", "Mad", "Excited", "Joyful"}
Dim charText As Char
charText = "_"
If txtDataEntry.Text.Contains(charText) Then ' if statement to determine if text contains a "_"
subString = txtDataEntry.Text.Substring(0, 4) 'sets variable subString to a substring of text data
For i = 0 To IdValues.Length - 1 'looping through array
If IdValues(i).Contains(subString) And txtDataEntry.Text.Contains(IdValues(i)) Then
MsgBox("Success, the position is at position " & i)
IdValues(i) = ValueValues(i) 'new array position now equals the IdValue array where the substring is found
lblValueResult.Text = IdValues(i) 'prints outcome to label
isValueFound = True
Exit For
End If
Next i
If isValueFound = False Then
MsgBox("Error : Not Found")
End If
Else
MsgBox("Sorry, no value was found.")
End If

Remove characters from a word - VBA

I want to remove characters from a string based on the position. i use the below code and i manage to:
Insert all word letters in an array
Loop the array and replace the letters that i want with nothing
BUT i dont know have to remove nothing from the array, recreate array index and create the word again without those characters.
'Create an array with all letters
For j = 1 To Len(SheetName2)
ReDim Preserve arrWord(k)
arrWord(k) = Mid(SheetName2, j, 1)
k = k + 1
Next j
Counter = (Len(SheetName2) - 31) * 2
'Loop array and replace with nothing
For w = Counter - 1 To 0 Step -2
arrWord(w) = ""
Next w
You don't need an array of the characters. Just read every second character into a new string.
Public Sub OutputEverySecondChar()
Dim TestString As String
TestString = "abcdefghij"
Dim OutputString As String
Dim iChar As Long
For iChar = 1 To Len(TestString) Step 2
OutputString = OutputString & Mid$(TestString, iChar, 1)
Next iChar
Debug.Print OutputString 'output is: acegi
End Sub
Or even better as re-useable function:
Public Sub test()
Debug.Print ReturnEveryXcharcter(InputString:="abcdefghij", FirstChar:=1, xChar:=2, CharLength:=1)
End Sub
Public Function ReturnEveryXcharcter(InputString As String, FirstChar As Long, xChar As Long, CharLength As Long) As String
Dim iChar As Long
For iChar = FirstChar To Len(InputString) Step xChar
ReturnEveryXcharcter = ReturnEveryXcharcter & Mid$(InputString, iChar, CharLength)
Next iChar
End Function
So the function is even more flexible and you can eg use the following to delete every 3ʳᵈ character (beginning with the first):
Debug.Print ReturnEveryXcharcter(InputString:="abcdefghij", FirstChar:=2, xChar:=3, CharLength:=2)
'output will be: bcefhi
Edit according comment:
Then loop until it is less then 31 characters:
Public Sub test()
Dim SheetName As String
SheetName = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
Do
SheetName = ReturnEveryXcharcter(InputString:=SheetName, FirstChar:=1, xChar:=2, CharLength:=1, LengthLimit:=31)
Loop While Len(SheetName) > 31
Debug.Print SheetName
End Sub
My solution:
If Len(SheetName1) > 31 Then
SheetName2 = Replace(SheetName1, " ", "")
'Third check - Remove letter by letter starting from the beginning
If Len(SheetName2) > 31 Then
Counter = (Len(SheetName2) - 31) * 2
Part_1 = Left(SheetName2, Counter)
Part_2 = Mid(SheetName2, Counter + 1, Len(SheetName2) - (Counter))
Semi_Part = ""
For j = 1 To Counter Step 2
'Use only Part_1 because it ll be the same in all occurance
Semi_Part = Semi_Part + Mid(Part_1, j, 1)
Next j
FinalSheetname = Semi_Part & Part_2
Else
FinalSheetname = SheetName2
End If
Else
FinalSheetname = SheetName1
End If
Just for interest, you can also do this with a worksheet function if you have one of the more recent versions of Excel (O365 or 2016+) that has the CONCAT function.
The "trick" is to create an array that includes the positions of the characters you wish to retain.
In the case of deleting every even space positioned character (retaining the odd positions):
=CONCAT(MID(A1,(ROW(INDEX($A:$A,1,1):INDEX($A:$A,ROUNDUP(LEN(A1)/2,0),1))-1)*2+1,1))
Since this is an array formula, you need to "confirm" it by holding down ctrl + shift while hitting enter. If you do this correctly, Excel will place braces {...} around the formula as observed in the formula bar

Replacing Characters in an Array in VB.NET

I am trying to create a deciphering program which takes the entire English alphabet and shifts the letters' positioning to the left at one increment at a time. I have created a character array for this and I have got the shifting part to work. So, the index of each character in the array changes each time a shift is made. I also created an identical character array which does not shift so it has something to compare to.
Once the shift is made, I have textbox1 output into textbox2 which replaces the letters to their now corresponding letters based on the index of the first character array. For instance, "ABC" is now "DEF". The problem I am having is upon replacing the characters, it will replace them again because their state was changed previously. For example, I changed "A" to "B". Then I move on to changing "B" to "C". But since the "A" was changed to a "B", it is changed again to a "C". I realize doing a For Each Loop caused this to happen so I took it out of a loop and it still does it. I even tried putting a break in the code such as GOTO but that just stops the loop after changing the first letter.
Here is my code:
Private Sub cryptshift()
'SHIFTING ALL CHARACTERS IN ARRAY ONE SPACE TO THE LEFT
Dim temporaryStorageA As [String] = charArray(0)
Dim temporaryStorageB As [String]() = New [String](charArray.Length - 1) {}
For i As Integer = 1 To charArray.Length - 1
temporaryStorageB(i - 1) = charArray(i)
charArray(i - 1) = temporaryStorageB(i - 1)
Next
charArray(charArray.Length - 1) = temporaryStorageA
'CLEARING LABEL54 AND REALIGNING ARRAY TO LABEL53
Label54.Text = Nothing
For Each c In charArray
Label54.Text = Label54.Text & c & "-"
Next
'DECIPHERING
Dim mess As String = TextBox1.Text
Dim result As String = ""
For i As Integer = 0 To mess.Length - 1
Dim c As Char = mess(i)
Dim itemindex As Integer = Array.IndexOf(charArray2, c)
'**This IF Statement allows letters to be deciphered but also allows other characters such as punctuation, numbers and spaces to go through without any altering.**
If charArray2.Contains(c) Then
result &= charArray(itemindex)
Else
result &= c
End If
Next
TextBox2.Text = result
End Sub
Your problem is the .Replace. You should change only the current character. Here, I'm creating a new string with the result.
Dim mess As String = TextBox1.Text
Dim result As String = ""
For i As Integer = 0 To mess.length-1
Dim c As Char = mess(I)
Dim itemindex As Integer = Array.IndexOf(charArray2, c)
result &= charArray(itemindex)
Next
You could then use a string building.

Regex expression and match function in text file

I have problem with my matching function actually I have to count number of lines with specific string and return line number ,so I have one dimensional array of string that contain the unique strings of text file {33,7,77,3 23,6} and text file with the same strings in array I have read lines of text file to array , but with duplicate of these strings ,when I use regex.match it works not bad expect when I check if line 2 contain 3 the function return True it's consider 3 in 23 as 3 , and the above explanation is just example of what I need any help please
Module Module1
Sub Main()
Dim txt As String = File.ReadAllText("e:\ii.txt")
' Use regular expressions to replace characters
' that are not letters or numbers with spaces.
Dim reg_exp As New Regex("[^a-zA-Z0-9]")
txt = reg_exp.Replace(txt, " ")
' Split the text into words.
'Dim words() As String = txt.Split( _
' New Char() {" "c}, _
' StringSplitOptions.RemoveEmptyEntries)
Dim words = txt.Split(New String() {" ", Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
' Use LINQ to get the unique words.
Dim word_query = _
(From word As String In words _
Order By word _
Select word).Distinct()
Dim stra() As String = word_query.ToArray()
For i = 0 To stra.Length - 1
Console.WriteLine(" " & stra(i))
Next
Dim lines() As String = IO.File.ReadAllLines("e:\ii.txt")
For i = 0 To lines.Length - 1
Console.WriteLine(lines(1))
Dim linecount = 0
Dim regex As New Regex(stra(i), RegexOptions.ExplicitCapture)
Dim match As Match = regex.Match(lines(1))
If match.Success Then
linecount += 1
Console.WriteLine("linecount= " & linecount)
Else
Console.WriteLine("false")
End If
Next
End Sub
End Module
You many not have to split the text into words. Is your word list very long? From what I understand you want the following:
1.Read a text file and return the line number for a given word or phrase.
Is the word or phrase complex? If not, why not use a the Contains extension method?
For example:
Dim myString = "Hello World"
If myString.Contains("World") Then
'Add line number to line count.
End if
If you are using this as an opportunity to learn regular expressions, I highly recommend "Mastering Regular Expressions" by Jeffrey Friedl. When I first begun I invested in a program RegexBuddy, which is worth the money. But now there are so many online regex testers now, that could be an alternative for something free.
Enhance your regex with anchors. These will ascertain that the whole test string matches instead of a substring. The following code also assembles all match patterns of interest into a single regex pattern which will be used against each line of the target file:
Dim strall As String
strall = ""
For i = 0 To stra.Length - 1
If i > o Then
strall = strall & "|"
End If
strall = strall & stra(i)
Console.WriteLine(" " & stra(i))
Next
strall = "^(" & strall & ")$"
Dim regexall As New Regex(strall, RegexOptions.ExplicitCapture)
'...
Dim linecount = 0
Dim match As Match = regexall.Match(lines(i)) '... was 'lines(1)', probably a typo
If match.Success Then
'...
this code is working with me thanks for all
Public Function countlines(ByVal st As String) As Integer
Dim count As Integer
Dim linecount As Integer = 0
Dim substrings() As String = Regex.Split(st, " ")
Dim stt() As String = {23, 7, 3}
For i = 0 To stt.Length - 1
'For j = 0 To substrings.Length - 1
'Console.WriteLine(substrings(0))
'For i = 0 To substrings.Length - 1
'Console.Write(substrings(i))
Dim matchQuery = From word In substrings Where word.ToLowerInvariant() = stt(i).ToLowerInvariant() Select word
' ' Count the matches.
count = matchQuery.Count()
Console.WriteLine("count=" & count)
If count > 0 Then
linecount += 1
Else
Console.WriteLine(" linecount=" & linecount)
End If
Next
Console.WriteLine("linecount= " & linecount)
Return linecount
End Function
Sub Main()
Dim lines() As String = IO.File.ReadAllLines("e:\ii.txt")
For Each line As String In lines
countlines(line)
Next
End Sub

Array go out of bounds in VB

I'm currently working on a program that will convert a string into "combined integer" (namely: from a string, it will be splitted into two characters at a time and then each character in each group will be converted into ASCII number. Then, the first character is multiplied by 256 (shift 8 bit to the left) and add second character. It must not eliminate/forget any character inside the string
Here is when the trouble really begin: it threw IndexOutOfRangeException
Dim input As String = TextBox1.Text.PadLeft(1)
Dim charArr As Char() = input.ToCharArray
Dim intGroup As UShort
Dim strout As String = ""
For index = 0 To charArr.Length - 2 Step 2
Dim i = index
Dim a = charArr(i)
Dim b = charArr(i + 1)
intGroup = CByte(AscW(a)) * 256 + CByte(AscW(b))
strout = strout + CStr(intGroup) + " "
Next
MsgBox(strout)
My guess was that I modify the index inside the loop which is 'forbidden'.
Any possible solution??
Thanks
I would do something like this but I don't know how you want to deal with odd length strings:
For index = 0 To charArr.Length - 1 Step 2
Dim a = charArr(index)
Dim b = If(index=charArr.Length - 1, _
<something to use for odd length strings>, _
charArr(index + 1))
intGroup = CByte(AscW(a)) * 256 + CByte(AscW(b))
strout = strout + CStr(intGroup) + " "
Next
I don't know what you want to use, especially if you bear in mind that .NET strings (unlike, say, C strings) can perfectly well contain a character with ascii code 0, so just using 0 may leave you with ambiguous data, depending on how you're using this string that you're constructing.
But basically, it comes down to you needing to do some special handling for odd length strings, and no magic manipulation of the for loop parameters will avoid that fact - you either deal with them in the loop (as above) or use a shorter loop (.Length - 2) and perform a length check afterwards and deal with the final character that you missed in the loop separately.
For index = 0 To input.Length - 2 step 2
array its zero based, so if the lenght = n, last element is arr[n-1].
for handle only odds element, the last element its arr[n-2].

Resources