I'm working on this project, in Visual Basic:
Sub Main()
Dim i As Integer, j As Double
i = 1
Dim fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\text.txt")
For i = 1 To 3
Dim stringReader = fileReader.ReadLine()
j = j + CDbl(stringReader)
Next
Debug.Print(j)
End Sub
Which is supposed to read the first three lines of a text file containing:
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
Now when these numbers are added up, and the result is printed, it gives me scientific notation, so here is my question:
Is there a way I can make the program write the whole number without scientific notation, AND all the significant figures, I seem to get a problem where past 10 ~ 12 digits it's just all 0.
I know similar questions have been asked but I can't seem to find an answer to apply to my case, so I'm sorry if it is a duplicate.
You can use something like this. This will avoid E exponential format of numbers.
YourNumber.ToString(".################") 'No of digits = No of hashes #
Related
basically, I want to reverse the numbers. (in the textbox there will be only 2-digit numbers)
if I have Textbox1.text:
12
2
41
71
70
I want to display in the box (Textbox1.text)
21
2
14
17
70
Function:
Public Shared Function Reverse(num As Integer) As Integer
Dim _reverse As Integer = 0
While num <> 0
_reverse *= 10
_reverse += num Mod 10
num \= 10
End While
Return _reverse
End Function
it should work, it actually works, but I don't know how to arrange it to work in all lines.
For Each lines In TextBox1.Lines
Dim rev = Reverse(lines)
lines.Replace(lines, rev)
Next
This is a perfect example of what happens when people try to write code without knowing what the code is supposed to. What the code is supposed to do is not just the end result but the steps to get there. If you don't know what the steps are then you shouldn't be writing any code because it's unlikely that what you write will do anything useful. Code is simply an implementation of logic so you should be getting the logic down first. It doesn't take any programming experience to work out the logic because we could all do this if it was a manual process and that would be the same logic.
So, what are the steps involved?
Get the lines of the text.
Loop over the lines.
Reverse the current line.
Replace the original line with the result of reversing.
Replace the text with the complete results.
If you actually consider each of those steps, it should be obvious that you cannot use a For Each loop because that will only let you get data out of a list, not put data into it. That would make it obvious that a For loop is the right choice, because will let you get data out and put it in. Now you can write code that actually does something useful.
Dim lines = TextBox1.Lines
For i = 0 To lines.GetUpperBound(0)
Dim line = lines(i)
Dim number = CInt(line)
Dim result = Reverse(number)
lines(i) = result.ToString()
Next
TextBox1.Lines = lines
Simple stuff but, again, if you don't know what the code has to actually do, writing code to do it is a challenge. Always break the problem down into smaller parts first, so you can work on each part individually, and always work out the logic you're trying to implement - and test that logic manually - before trying to write code to implement it.
i m working with richtextbox which contains words and sentences...... but i need to convert long words into two parts or break long words like 8 characters or more then 8 characters words into tow parts.... but if word contains 9 characters i want to make two words one of 4 characters and other into 5 characters
im doing spell checker where i use permuduction and combination method which allows me to handle onley 8 chracters long word. so i want to break long words into parts
ix = 0
Label6.Text = 0
For ix = Label6.Text To RichTextBox1.TextLength
str = Mid(RichTextBox1.Text, ix, 1)
If str = "آ" Or str = "ا" Or str = "ب" Or str = "ٻ" Or str = "ڀ" Or str = "ت" Or str = "ٿ" Or str = "ٽ" Or str = "ٺ" Then
tillword = tillword & str
Label6.Text = tillword.Length
End If
Next
Welcome to Stack Overflow!
What you want to do can be considered a special case of hyphenation, even if you aren't actually splitting the words at the end of the line and/or adding the customary dashes that indicate a hyphenation. Since you're just starting out here, I've gone and done as Mary suggested in a direct comment to your question -- used String.Split() to get a list of words, and an instance of StringBuilder to rebuild the string, as shown in the code below. This console app code should get you started, though still you'll have to work out a few of the issues yourself, or traverse some of the links at the bottom to produce better output (if needed):
Module Module1
Sub Main()
Dim test1 As String = "The Quick Brown Fox in Missisippi Jumped over the Lazy Dog in Tallahassee,
and told his cousin in Texarkansas, saying the word antidisestablishmentarianism while doing it."
Dim wrds As String() = test1.Split()
Dim wrd As String
Dim part1 As String
Dim part2 As String
Dim sb As Text.StringBuilder = New System.Text.StringBuilder()
For Each wrd In wrds
If wrd.Length > 8 Then
part1 = wrd.Substring(0, 8)
part2 = wrd.Substring(8)
sb.Append(part1)
sb.Append(" ")
sb.Append(part2)
sb.Append(" ")
Else
sb.Append(wrd)
sb.Append(" ")
End If
Next
Dim finalAnswer As String = sb.ToString()
Console.WriteLine(finalAnswer)
Console.WriteLine()
Console.ReadLine()
End Sub
End Module
and here is the output from the above program:
The Quick Brown Fox in Missisip pi Jumped over the Lazy Dog in Tallahas see,
and told his cousin in Texarkan sas, saying the word antidise stablishmentarianism while doing it.
Note that I've given you what you asked for, but not necessarily what you really want -- the last part of antidisestablishmentarianism is still too long, the strings, as split, are not pleasing to read. That's why it's really not that easy, and in my opinion, there's almost an art to it. Therefore...
Following is further information and some links for your to make sure it's what you want.
First, Here is one person's Pseudocode for a recursive solution close to what you want.
Second, from another developer (Bjarke Ebert),
Donald E. Knuth did a lot of work on the line breaking algorithm in
his TeX typesetting system. This is arguably one of the best
algorithms for line breaking - "best" in terms of visual appearance of
result.
And third, some good suggestions from JasCav here:
Obviously, Donald Knuth's algorithms are excellent. Although there is
not a C# implementation available, have you considered converting
another implementation to C#? (For example, you could convert the Java
implementation which is fairly close to C#.)
HTH.
How would I go about storing a very large number in number format and not scientific.
Please bear in mind that the number I will be storing is too big for the Long data type.
I've set it as a String.
I have a userform with a command button and a textbox.
Below is the sample code:
Private Sub Cmd_Click()
Dim bits As Integer
Dim out As String
bits = 64
out = 2 ^ (bits - 1)
Txt_Output.Value = out
End Sub
The above will return: 9.22337203685478E+18.
But I want 9223372036854775807.
Can anyone explain how to avoid this?
Thanks in advance.
P.S. I'm hoping to avoid having to use an array.
You can achieve that specific calculation using Decimal data types and a modification to the calculation routine:
Private Sub Cmd_Click()
Dim bits As Integer
Dim out As Variant
Dim i As Long
bits = 64
out = CDec(1)
For i = 1 to bits - 1
out = out * 2
Next
Txt_Output.Value = out
End Sub
By forcing out to be a Variant/Decimal, the calculation does not lose precision as it is being calculated. However some things, such as CDec(2) ^ CDec(63) would still lose precision as the calculation would be done using an intermediate Double precision, so you will need to be very careful as to what calculations you do.
This might give you clues as to how to generalise that method to achieve what you need.
If you have 64-bit Excel, you can use the LongLong data type.
Hey guys I'm trying to make a program that helps people encrypt messages and decrypt messages using the Caesar shift cipher, I know it's probably already been done, I want to have a go myself though.
The problem I've been having is when it comes to encrypting the text. The user selects a number (between 1-25) and then the application will change the letters corresponding to the number chosen, e.g. if the user inputs "HI" and selects 2, both characters are moved two places down the alphabet outputting "JK". My main problem is the replacing characters though, mostly because I've set up the program to be able to encrypt large blocks of text, because my code is:
If cmbxKey.Text = "1" Then
If txtOutput.Text.Contains("a") Then
sOutput = txtOutput.Text.Replace("a", "b")
txtOutput.Text = sOutput
End If
If txtOutput.Text.Contains("b") Then
sOutput = txtOutput.Text.Replace("b", "c")
txtOutput.Text = sOutput
End If
End If
This means if the user inputs "HAY" it will change it to "HBY" and then because of the second if statement it will change it to "HCY" but I only want it to be changed once. Any suggestions to avoid this???? Thanks guys
Since you want to shift all characters, start out by looping though the characters using something like ToArray:
For each s as string in txtOutput.Text.ToArray
'This will be here for each character in the string, even spaces
Next
Then, rather than having cases for every letter, look at it's ascii number:
ACS(s)
...and shift it by the number you want to. Keep in mind that if the number is greater than (I don't know if you want upper/lower case) 122, you want to subtract 65 to get you back to "A".
Then you can convert it back into a character using:
CHR(?)
So this might look something like this:
Dim sb as new text.StringBuilder()
For each s as string in txtOutput.Text.ToArray
If asc(s) > 122 Then
sb.append(CHR(ASC(s) + ?YourShift? - 65)
Else
sb.append(CHR(ASC(s) + ?YourShift?)
END IF
Next
txtOutput.Text = sb.ToString
A very simple method of changing your application while keeping your strategy is to replace the lower case characters with upper case characters. Then they won't be recognized by the Replace method anymore.
Obviously, the problem is that you want to implement an algorithm. In general, an algorithm should be smart in the sense that you don't have to do the grunt work. That's why a method such as the one presented by Steve is smarter; it doesn't require you to map each character separately, which is tedious, and - as most tedious tasks - error prone.
One big issue arise when you're facing a String that the basic Alphanumeric table can't handle. A String that contains words like :
"Déja vu" -> The "é" is going to be what ?
And also, how about encoding the string "I'm Aaron Mbilébé" if you use .ToUpper().
.ToUpper returns "I'M AARON MBILÉBÉ".
You've lost the casing, and how do you handle the shifting of "É" ?
Of course, a code should be smart as pointed above, and I was used to deal with strings just by using the System.Text.ASCIIEncoding to make things easier. But from the moment I started to use large amount of textual datas, sources from the web, files (...) I was forced to dig deeper, and seriously consider string encoding (and System Endianness by the way, when coding and decoding string to/from array of bytes)
Re-think of what do you really want in the end. If you're the only one to use your code, and you're certain that you'll only use A..Z, 0..9, a..z, space and a fixed amount of allowed characters (like puntuation) then, just build a Table containing each of those chars.
Private _AllowedChars As Char() = { "A"c, "B"c, ... "0"c, "1"c, .. "."c, ","c ... }
or
Private _AllowedChars As Char() = "ABCDEF....012...abcd..xyz.;,?:/".ToCharArray()
Then use
Private Function ShiftChars(ByVal CurrentString As String, ByVal ShiftValue As Integer) As String
Dim AllChars As Char() = CurrentString.ToCharArray()
Dim FinalChars As Char()
Dim i As Integer
FinalChars = New Char(AllChars.Length - 1) {} ' It's VB : UpperBound is n+1 item.
' so n items is UpperBound - 1
For i = 0 To AllChars.Length - 1
FinalChars(i) = _AllowedChars((Array.IndexOf(_AllowedChars, AllChars(i)) + ShiftValue) Mod _AllowedChars.Length)
Next
Return New String(FinalChars)
End Function
And
Private Function UnShiftChars(ByVal CurrentString As String, ByVal ShiftValue As Integer) As String
' ... the same code until :
FinalChars(i) = _AllowedChars((Array.IndexOf(_AllowedChars, AllChars(i)) - ShiftValue + _AllowedChars.Length) Mod _AllowedChars.Length)
' ...
End Function
^^ Assuming ShiftValue is always positive (defined once)
But again, this only works when you have a predefined set of allowed characters. If you want a more flexible tool, you ought to start dealing with encodings, array of byte, BitConverter and have a look at system endianness. That's why I asked if someone else is goind to use your application : let's try this string :
"Xin chào thế giới" ' which is Hello World in vietnamese (Google Trad)
In that case, you may give up..? No ! You ALWAYS have a trick in your cards !
Just create your allowed chars on the fly
Private _AllowedChars As New SortedList(Of Char, Char)
-> get the string to encode (shift)
Private Function ShiftChars(ByVal CurrentString As String, ByVal ShiftValue As Integer) As String
Dim AllChars As Char() = CurrentString.ToCharArray()
Dim FinalChars As Char()
Dim i As Integer
' Build your list of allowed chars...
_AllowedChars.Clear()
For i = 0 To AllChars.Length - 1
If Not _AllowedChars.ContainsKey(AllChars(i)) Then
_AllowedChars.Add(AllChars(i), AllChars(i))
End If
Next
' Then, encode...
FinalChars = New Char(AllChars.Length - 1) {}
For i = 0 To AllChars.Length - 1
FinalChars(i) = _AllowedChars.Keys.Item((_AllowedChars.IndexOfKey(AllChars(i)) + ShiftValue) Mod _AllowedChars.Count)
Next
Return New String(FinalChars)
End Function
The same for Unshift/decode.
Note : in foreing languages, the resulting string is pure garbage and totally unreadable, unless you (un)shift the chars again.
However, the main limitation of this workaround is the same as the fixed chars array above : Once you encode your string, and add a char in your encoded string that doesn't exists in the initial generated allowed chars, then you've nuked your data and you won't be able to decode your string. All you'll have is pure garbage.
So one day... one day maybe, you'll have to dig deeper at the byte level of the thing, in a defined extended encoding (Unicode/UTF8/16) to secure the integrity of your data.
I'm trying to read two matrix from a binary file (256x256x2) but couldn't do it without iterating 256x256x2 times which takes too long. For now I just want to check the data and make sure it's corect (not only zeros). This is what I have:
Dim msg As String
Dim b(256 * 256 * 2) As Byte
Dim i As Int32
Dim reader As New BinaryReader(File.Open(path, FileMode.Open))
b = reader.ReadBytes(b.Length)
For i = 0 To b.Length
msg = msg & ", " & b(i)
Next
TextBox1.Text = msg
The data on the matrix are just numbers (0-255).
What's the best way to save the data to an array, if possible with the format
array[matrixno][row][column]
because later I will need to find specific values of the array based on its position.
PS. I'm using the old Visual Studio 2003 because that's what I have available.
Thanks
Edit:
Figured out what was taking long was actually displaying all the bytes, problem solved!
Almost two years later, it's time to take this off the unanswered list.
The loop worked just fine, the problem was printing every single value read instead of simpling saving it to a variable.
Lesson learned (long ago): Printing takes time.