I was assigned the following project for my VB.Net programming course:
"Write a program using various procedures to perform the operations listed below. Call these procedures using delegates. Make sure to document your program and have the program print descriptive text along with the numbers in b. and c.
a) Print a text string in reverse word order.
b) Print the number of characters in the string.
c) Print number of words in the string."
Now this raises a couple of questions that I have (some of which are opinion-based) relating to how I should complete the assignment.
First off, what do you guys think my teacher means by "reverse word order"? Do they mean print a text string with the word compositions going backwards (i.e. "siht si a ecnetnes"), do they mean print a text string with the whole words going backwards (i.e. "sentence a is this"), or do they mean both at once (i.e. "ecnetnes a si siht")? This is one of the opinion-based questions, but I just wanted your guys' thoughts.
Secondly, what is the syntax to produce the number of characters in a string? I already know the code necessary to get the number of words, but part b of this assignment is confusing me slightly. Any help would be greatly appreciated.
For your second question, the syntax to produce the number of characters in a string is:
Dim mystring as String = "This is a string"
Console.Writeline(mystring.Length)
// outputs 16
As I mentioned in my comments, my guess for your first question is that the teacher wants the words reversed, not the characters, so "this is a sentence" would appear in reverse as "sentence a is this"
Had a quick go at this because it sounded interesting.
' Reverse the string and then print it to the output window
Dim ReverseArray As Array = "Print a text string in reverse word order.".ToCharArray
' Reverse the array to
Array.Reverse(ReverseArray)
' Convert the array back into a string (should be Reversed...)
Debug.WriteLine("Reversed string = '{0}'", New String(ReverseArray))
' Get the number of Characters, remember a "Space" is still a Character
Debug.WriteLine("Number of characters in array = {0}", ReverseArray.Length)
' Count the number of spaces in the string, then add an extra one
Debug.WriteLine("Number of Words = {0}", (From c In ReverseArray Where c.ToString = " " Select c).Count + 1)
Related
Hey so i have a school project in which i need to split a massive word into smaller words.
This is the massive sequence of letters :
'GLSDGEWQQVLNVWGKVEADIAGHGQEVLIRLFTGHPETLEKFDKFKHLKTEAEMKASEDLKKHGTVVLTALGGILKKKEGH
HEAELKPLAQSHATKHKIPIKYLEFISDAIIHVLHSKHRPGDFGADAQGAMTKALELFRNDIAAKYKELGFQG'
and then i need to split it into other smaller separate parts of itself which would look like this :
'GLSDGEWQQVLNVWGK'
'VEADIAGHGQEVLIR'
'LFTGHPETLEK'
'FDK'
'FK'
'HLK'
'TEAEMK'
'ASEDLK'
'K'
'HGTVVLTALGGILK'
'K'
'K'
'EGHHEAELKPLAQSHATK'
'HK'
'IPIK'
'YLEFISDAIIHVLHSK'
'HRPGDFGADAQGAMTK'
'ALELFR'
'NDIAAK'
'YK'
'ELGFQG'
i have no idea how to start on this if you could help pls and thanks
Different digestion enzymes cut at different positions within a protein sequence; the most commonly used one is trypsin. It follows the following rules: 1) Cuts the sequence after an arginine (R) 2) Cuts the sequence after a lysine (K) 3) Does not cut if lysine (K) or arginine (R) is followed by proline (P).
Okay, hooray, rules! Let's turn this into pseudo-code to describe the same algorithm in a half-way state between the original prose and code. (While a Regex.Split approach would still work, this might be a good time to explore some more fundamentals.)
let the list of words be an empty array
let current word be the empty string
for each letter in the input:
if the letter is R or K and the next letter is NOT P then:
add the letter to the current word
save the current word to the list of words
reset the current word to the empty string
otherwise:
add the letter to the current word
if after the loop the current word is not the empty string then:
add the current word to the list of words
Then let's see how some of these translate. This is incomplete and quite likely contains minor errors1 beyond that which has been called out in comments.
Dim words As New List(Of String)
Dim word = ""
' A basic loop works suitably for string input and it can also be
' modified for a Stream that supports a Peek of the next character.
For i As Integer = 0 To input.Length - 1
Dim letter = input(i)
' TODO/FIX: input(i+1) can access an element off the string. Reader exercise.
If (letter = "R"C OrElse letter = "K"C) AndAlso Not input(i+1) = "P"C
' StringBuilder is more efficient for larger strings
Set word = word & letter
words.Add(word) ' or perhaps just WriteLine the word somewhere?
Set word = ""
Else
Set word = word & letter
End If
Next
' TODO/FIX: consider when last word is not added to words list yet
1As I use C# (and not VB.NET) the above code comes warranty Free. Here are some quick reference links I used to 'stitch' this together:
https://www.dotnetperls.com/loop-string-vbnet
https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/operators-and-expressions/concatenation-operators
https://www.dotnetperls.com/list-vbnet
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/dim-statement
How do you declare a Char literal in Visual Basic .NET?
I'm trying to create a function which generates a secret encoded message. It takes in three things: a string, for example, "testingtestingonetwothree", as well as the desired number of characters, for example 5, and the desired number of words, for example 5. It generates the message by starting at the first character, and extracting every fifth character through the string, putting these characters into a codeword, then starting at the second character and extracting every fifth character through the string, putting these into a second codeword, and so on. It just outputs a string, with the codewords separated by a space. So for this example it would produce: "tntnt egieh stntr tegwe isooe".
I'm okay at coding but new to VBA. I've made what I think is a valid function, but when it's used in the spreadsheet I get a #VALUE! error: "A value used in the formula is the wrong data type". This is the user defined function I made:
Function encode(strng, numchars, numwords)
Dim word As Integer
Dim step As Integer
Dim temp As String
Dim output As String
For word = 1 To numchars
step = word
temp = ""
Do While step <= Len(strng)
temp = temp & Mid(strng, 1, step)
step = step + numchars
Loop
If word = 1 Then output = temp Else output = output & " " & temp
Next word
encode = output
End Function
And when it's used in the spreadsheet I just call it, as in
=encode(A16,A7,A10)
Where A16 contains testingtestingonetwothree, A7 contains 5 and A10 contains 5.
Does my function seem okay? And is there anything you guys can see which could be giving the value error? Any help would be greatly appreciated, thanks a lot for reading.
EDIT: This now outputs a value, but the wrong value. It outputs: "ttestintestingtesttestingtestingontestingtestingonetwot tetestingtestingtestitestingtestingonetestingtestingonetwoth ", when it should output: "tntnt egieh stntr tegwe isooe". Is there anything you guys can see that my function is doing wrong?
EDIT2: After fixing the Mid function, to
temp = temp & Mid(strng, step, 1)
as per vacip's answer, the function now produces the correct answer.
Ok, everyone says it works, but for me, it doesn't produce the desired output. What the...???
Anyway, I think your Mid function is in the wrong order, try it like this:
temp = temp & Mid(strng, step, 1)
Also, make sure to properly declare your variables, like this:
Function encode(strng As String, numchars As Integer, numwords As Integer) As String
I have also rewritten your IF statement, that one-line thing is strange for me...
If word = 1 Then
output = temp
Else
output = output & " " & temp
End If
This way it worked for me.
Other people have addressed the type problem. Here is a different suggestion. The cipher that you are describing is a simple transposition cipher, specifically a columnar transposition ( https://en.wikipedia.org/wiki/Transposition_cipher#Columnar_transposition )
The way people did this pre-computer was to write the characters into a grid row by row then read them off column by column. In fact -- this is probably still the easiest way to implement it even with computers. Declare a variant which can be redimensioned to be an array with e.g. 5 columns (where 5 is the skip between letters) and the number of rows is chosen to be large enough so that the grid can hold the string. After you load up the characters row by row, read them off column by column using nested for loops.
Once you get a basic example working, you can try to implement a version which uses a key to determine the order that you read off the columns for added security.
Coding classical cryptography/cryptanalysis as an excellent way to learn a programming language. Almost the first thing I do when I try to learn a new language is to implement a Vigenere cipher in it. Even though it is long out of print and can be somewhat tricky to translate to modern dialects of Basic the book "Cryptanalysis for Microcomputers" by Caxton Foster is great fun and can be purchased for just a few dollars from online used bookstores.
You need to define your Function's type. So in this case I believe you would want
Function encode(strng, numchars, numwords) As String
I tested your code exactly as it is, and it worked fine.
So, your problem may be:
A certain argument of your function is not the right type. (I bet the len method is the problem in there).
Check if A16 is really a string. If not, consider converting it to a string before if you want to pass numbers too:
Function encode(strng as variant, numchars as integer, numwords as integer) as string
strng = str(strng)
Check also if A7 and A10 are really integers.
I am writing a program in Visual Basic that writes and reads to and from a Microsoft Access Database. When reading from the database, one of the functions that I am trying to perform is to determine the number of lines in a multi-line string that was written to the database and then subsequently read from the database. Here's what I have tried so far with no luck.
Dim stringLines() As String = databaseReader("multilineString").ToString.Split(CChar("Environment.NewLine"))
Dim stringLinesCount As Integer = stringLines.Length
For some reason, this always results in stringLinesCount being equal to one, regardless of how many lines the string has. In this example, I am using Environment.NewLine, but I have tried \n, \r, vbCr, vbLf, and vbCrLf as well, and they all result in a value of one. Since none of these seem to be working, what can I use instead to determine the number of lines?
Edit:
Dim splitCharacters() As Char = {CChar(vbCrLf), CChar(vbCr), CChar(vbLf), CChar(Environment.NewLine), CChar("\n"), CChar("\r")}
Dim stringLines() As String = databaseReader("multilineString").ToString.Split(splitCharacters)
Dim stringLinesCount As Integer = stringLines.Length
Since Chris Dunaway provided the answer that I view as helpful but posted it as a comment, here's what he said:
VB cannot use C# style escape sequences, so CChar("\n") and CChar("\r") is meaningless in VB. Also, calling CChar("Environment.NewLine") is wrong because you are trying to convert the actual string "Environment.NewLine" to a single character, which obviously won't work. You can just use Environment.Newline directly in the call to String.Split.
If Chris decides to post his comment as an answer, please let me know so that I may remove this.
Foreign letters ÅÄÖ hve been replaced by other characters in my VBA-code. Both strings and range names have been affected. This has happened after I have sent the file to a client.
Obviously I could change the names of variables to not contain ÅÄÖ, although that would be somewhat tedious. But references to worksheets and other things that affect the user interface have also been messed up. Why has this happened? Can I stop it from happening?
Examples before:
MsgBox ("Ett oförutsätt fel har skett.")
Range("ActionsColumnAffärsläget")
Examples after:
MsgBox ("Ett ofšrutsŠtt fel har skett.")
Range("ActionsColumnAffŠrslŠget")
Instead of typing the characters directly you can replace them by referencing their character code in your message box string like so...
MsgBox("Ett of" + Chr(246) + "ruts" + Chr(228) + "tt")
It's stupidly verbose way of doing it but should work.
To avoid typing out Chr(###) everytime you need them you can put the characters you need in a short form variable like...
Dim a As String = Chr(228)
Dim o As String = Chr(246)
MsgBox("Ett of" + o + "ruts" + a + "tt")
Although I find Zack's solution much more elegant than mine (finally, you should type the code only once), here is a work around that will avoid you to write the code as a composition of characters:
Place your sentence in the range (for example) "A1" of the worksheet "Dictionary" that you will create;
Write in Range("A1") the value Ett oförutsätt fel har skett.
Change your code with MsgBox(Sheets("Dictionary").Range("A1")
Unfortunately there's no way to embedd special characters into the source code, you will need either one or the other work around (usually these are contained in XML files).
Hey guys I'm stuck with this question. Please help.
I want to write a program that can extract alphabetical characters and special characters from an input string. An alphabetical character is any character from "a" to "z"(capital letters and numbers not included") a special character is any other character that is not alphanumerical.
Example:
string = hello//this-is-my-string#capetown
alphanumerical characters = hellothisismystringcapetown
special characters = //---#
Now my question is this:
How do I loop through all the characters?
(the for loop I'm using reads like this for x = 0 to strname.length)...is this correct?
How do I extract characters to a string?
How do I determine special characters?
any input is greatly appreciated.
Thank you very much for your time.
You could loop through each character as follows:
For Each _char As Char In strname
'Code here
Next
or
For x as integer = 0 to strname.length - 1
'Code here
Next
or you can use Regex to replace the values you do not need in your string (I think this may be faster but I am no expert) Take a look at: http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx
Edit
The replacement code will look something as follows although I am not so sure what the regular expression (variable called pattern currently only replacing digits) would be:
Dim pattern As String = "(\d+)?" 'You need to update the regular expression here
Dim input As String = "123//hello//this-is-my-string#capetown"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, "")
Since you need to keep the values, you'll want to loop through your string. Keeping a list of characters as a result will come in handy since you can build a fresh string later. Then take advantage of a simple Regex test to determine where to place things. The psuedo code looks something like this.
Dim alphaChars As New List(Of String)
Dim specialChars As New List(Of String)
For Each _char As Char in testString
If Regex.IsMatch(_char, "[a-z]")) Then
alphaChars.Add(_char)
Else
specialChars.Add(_char)
End If
Next
Then If you need to dump your results into a full string, you can simply use
String.Join(String.Empty, alphaChars.ToArray())
Note that this code makes the assumption that ANYTHING else than a-z is considered a special character, so if needs be you can do a second regular expression in your else clause to test for you special characters in a similar manner. It really depends on how much control you have over the input.