My For Loop skips my IF statement - vb.net

I wonder if anyone can help. I am making a program that will convert Text to ASCII. However, I want my program to ignore spaces. Hence, "IT WAS A" should look like this: 7384 876583 65
When I use the Step Into Feature of VB I can see that my For loop is skipping my IF statement which should be giving me my spaces. I don't understand why. As you can probably tell, I am a beginner so any specific help would be greatly appreciated. My code looks like this:
Dim PlainText, ConvertedLetter As String
Dim LetterToConvert As Char
Dim AscNumber, Counter As Integer
ConvertedLetter = ""
PlainText = txtPlain.Text
For Counter = 1 To Len(PlainText)
LetterToConvert = Mid(PlainText, Counter, 1)
If PlainText = " " Then
ConvertedLetter = " "
Else : AscNumber = Asc(LetterToConvert)
ConvertedLetter = ConvertedLetter & AscNumber
End If
Next
txtAscii.Text = ConvertedLetter

Because you're comparing PlainText, which is the whole string, to " ". It would need to be:
If LetterToConvert = " " Then ....

Try this:
Dim PlainText, ConvertedLetter As String
ConvertedLetter = ""
PlainText = "IT WAS A"
For Each c As Char In PlainText 'iterate through each character in the input
If c <> " " Then ' check whether c is space or not
ConvertedLetter &= Asc(c).ToString()' ascii value is taken if c<>" "
Else
ConvertedLetter &= " " ' c is space means add a space
End If
Next
MsgBox(ConvertedLetter) ' display the result
You will get the output as
7384 876583 65

Related

vb.net position cursor one space greater than text box length

I have a TextBox and it contains this text "File Was Created"
I would like to place the cursor one space over from the end of this text in the TextBox
I am trying to NOT say Simple Enough Task BUT I have wasted 2 hours with no solution
YES I know if I change the text to this "File Was Created " it will work NOT a solution
Here is the code mess I have tried
Dim L As Integer
L = tbMessage.Text.Length
L += 1
'tbMessage.Text = CStr(L)
'tbHaveTwo.Text = frmOne.vR
'Me.ActiveControl = tbMessage
'tbMessage.SelectionStart = tbMessage.Text.Length
tbMessage.SelectionStart = L
tbMessage.Select()<br/>
Here is Two updated ways to solve this issue Jimi way less code
tbMessage.Text = "File Was Created"
'This Code involves more code
'Dim str As String
'str = Mid(tbMessage.Text, tbMessage.Text.Length)
'If str <> " " Then
' tbMessage.Text = tbMessage.Text & " "
'End If
'Answer from Jimi Works Great
tbMessage.AppendText(ChrW(32))
tbMessage.SelectionStart = tbMessage.Text.Length
tbMessage.Select()
So you don't end up with a ton of spaces on the end of your message?
tbMessage.AppendText(If(tbMessage.Text.EndsWith(" "), "", " "))
tbMessage.SelectionStart = tbMessage.TextLength
tbMessage.Focus()

Add text before specific characters

str as String = " " +"thisrocks" + " "
and strArray(0) = 123456sdv :'++':
so i want to add str before the :'++':, and then
strArray(0) = 123456sdv thisrocks :'++':
Is it possible ?
What could I do to search for it ? Regex maybe ?
str and strArray will already be there from previous codes. I just want to combine it int he right place.
Using the space in between will not be helpful as the strArray(0) could also be, dsf dsv dsgvsvs svs svssd bdsb sbdfb bsbb sb s sbsfbfsbsbfs :'++': and so on.
I can't control it as they come like that from previous codes and there is no way to fix them :/
I can't generalize the question since it is not clear enough, for this occasion you can use the following code to insert a string in between these two words
Dim str As String = " " + "thisrocks" + " "
Dim strArray(10) As String
strArray(0) = "123456sdv :'++':"
strArray(0) = strArray(0).Replace(":'++':", str & ":'++':")
Output will be
"123456sdv thisrocks :'++':"
Note:
this will work as, replace :'++': with & str and add :'++': to it so :'++': will stay their for the next replacement.
You can use String.IndexOf to find where the marker :'++': is and String.Insert to insert the required data:
Dim sample As String = "123456sdv :'++':"
Dim insertData As String = " thisrocks "
Dim marker As String = ":'++':"
Dim insertPos As Integer = sample.IndexOf(marker)
If insertPos >= 0 Then
sample = sample.Insert(insertPos, insertData)
End If
Console.WriteLine(sample) ' outputs "123456sdv thisrocks :'++':"

Left split, getting blank return.

Issue, where the character I am removing does not exist I get a blank string
Aim: To look for three characters in order and only get the characters to the left of the character I am looking for. However if the character does not exist then to do nothing.
Code:
Dim vleftString As String = File.Name
vleftString = Left(vleftString, InStr(vleftString, "-"))
vleftString = Left(vleftString, InStr(vleftString, "_"))
vleftString = Left(vleftString, InStr(vleftString, " "))
As a 'fix' I have done
Dim vleftString As String = File.Name
vleftString = Replace(vleftString, "-", " ")
vleftString = Replace(vleftString, "_", " ")
vleftString = Left(vleftString, InStr(vleftString, " "))
vleftString = Trim(vleftString)
Based on Left of a character in a string in vb.net
If File.Name is say 1_2.pdf it passes "-" and then works on line removing anything before "" (though not "" though I want it to)
When it hits the line for looking for anything left of space it then makes vleftString blank.
Since i'm not familiar (and avoid) the old VB functions here a .NET approach. I assume you want to remove the parts behind the separators "-", "_" and " ", then you can use this loop:
Dim fileName = "1_2.pdf".Trim() ' Trim used to show you the method, here nonsense
Dim name = Path.GetFileNameWithoutExtension(fileName).Trim()
For Each separator In {"-", "_", " "}
Dim index = name.IndexOf(separator)
If index >= 0 Then
name = name.Substring(0, index)
End If
Next
fileName = String.Format("{0}{1}", name, Path.GetExtension(fileName))
Result: "1.pdf"

Check if a string variable has an integer value

I am working on a project which allows kids to send a message to Santa. Unfortunately, if they enter a string instead of an integer in the AGE field, the program crashes and returns Conversion from string "[exampleString]" to type 'Double' is not valid.
Is there any way to check if they have entered an integer or not? This is the code.
If childAge > 0 And childAge < 150 Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
Thanks,
Kai :)
A very simple trick is to try parse the string as an Integer. If it succeeds, it is an integer (surprise surprise).
Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
' childAge successfully parsed as Integer
Else
' childAge is not an Integer
End If
Complementing Styxxy's response, if you dont need a result just replace it by vbNull:
If Integer.TryParse(childAge, vbNull) Then
You could perform the following two tests to be reasonably certain that the input you're getting is an integer:
If IsNumeric(childAge) AndAlso (InStr(1, childAge, ".") <> 0) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
If childAge < 0 OrElse childAge > 150 Then
fmSecA2 = "I don't believe it's possible to be" & childAge & " years old..."
End If
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
The InStr function returns zero if it doesn't find the string that is being looked for, and so when combining that test with IsNumeric, you also rule out the possibility that some floating point data type was entered.
IsNumeric is built into VB, and will return a true/false
If IsNumeric(childAge) AndAlso (childAge > 0 And childAge < 150) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
You can use this.
Sub checkInt()
If IsNumeric(Range("A1")) And Not IsEmpty(Range("A1")) Then
If Round(Range("A1"), 0) / 1 = Range("A1") Then
MsgBox "Integer: " & Range("A1")
Else
MsgBox "Not Integer: " & Range("A1")
End If
Else
MsgBox "Not numeric or empty"
End If
End Sub
Working from Styxxy's answer, if you parse as a byte rather than an integer, then it also checks negative ages and maximum age of 255 all in one go.
Dim childAgeAsByte As Byte
If Byte.TryParse(childAge, childAgeAsByte) Then
' childAge successfully parsed as Byte
Else
' childAge is not a Byte
End If
Kristian
Dim Input
Input = TextBox1.Text
If Input > 0 Then
............................
............................
Else
TextBox2.Text = "Please only enter positive integers"
End If
Try
If TextBox1.Text > 0 Then
Label1.Text = "Integer"
End If
Catch ex As Exception
Label1.Text = "String"
End Try
With this you can put anything in TextBox1, if you put text then you get Label1 is string and if you put number then you get it's integer
In .Net you may use GetType() to determine the data type of a variable.
Dim n1 As Integer = 12
Dim n2 As Integer = 82
Dim n3 As Long = 12
Console.WriteLine("n1 and n2 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n2.GetType()))
Console.WriteLine("n1 and n3 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n3.GetType()))
' The example displays the following output:
' n1 and n2 are the same type: True
' n1 and n3 are the same type: False
Based on the above sample you can write a code snippet:
If childAge.GetType() = "Integer" then '-- also use childAge.GetType().Name = "Int32"
' do something
End if
Reference MSDN

Trim last "," delimiter of a string in VB.NET

This is my code:
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= .Rows(i)("name") & ", "
End If
Next
End With
temp = temp.Trim(",")
testing &= "&Name=" & temp & vbCrLf
With this is get a comma in the end of the string. But if I do
temp = temp.Trim.Trim(",")
all commas are deleted.
How do I keep all commas and only delete the last one?
temp = temp.TrimEnd(CChar(","))
That will do it and I think it is the easiest way.
temp = temp.Trim().Substring(0, temp.Length - 1)
or
temp = temp.Trim().Remove(temp.Length - 1)
You can avoid the Trim/extra character if you set a delimiter within the loop
Dim delimiter as string = ""
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= delimiter & .Rows(i)("name")
delimiter = ","
End If
Next
The Trim() function has a Char() (static array of characters) parameter on it, you don't need to pass a Char explicitly.
' VB.Net Version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({" "c, ","c})
//C# version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({' ', ','})
Would produce the output
"Hello ^_^ ^_^"
The multi-parameter .Trim() removes the specified characters from both the beginning and the end of the string. If you want to only trim out the beginning or the end, use .TrimStart() or .TrimEnd() respectively.
This works:
dim AlarmStr as string="aaa , bbb , ccc , "
AlarmStr = AlarmStr.Remove(AlarmStr.LastIndexOf(","))
Check to see if the loop is done before adding the last comma. #cleaner
While dr.Read
For c As Integer = 0 To dr.FieldCount - 1
s.Append(dr(c).ToString.Trim)
'This line checks if the loop is ending before adding a comma
If (c < dr.FieldCount - 1) Then s.Append(",")
Next
s.Append(vbCrLf)
End While
I wonder, that based on the OP's code sample, nobody suggested to use String.Join or build an output with StringBuilder
Dim names As New List(Of String)
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
' DataRow("columnName").ToString() returns value or empty string if value is DbNull
If .Rows(i)("name").ToString() <> "" Then
names.Add(.Rows(i)("name"))
End If
Next
End With
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
With LINQ and DataRow extension method .Field(Of T) code will look simpler
Dim names = ad.Tables(2).
AsEnumerable().
Select(row => row.Field<String>("name")).
Where(name => String.IsNullOrEmpty(name) = False)
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
If you go further you can(should) use StringBuilder for building a string and use Aggregate method to build string from the collection
I know that a little bit odd, but I found this works for me:
Visual Basic:
Every time: mystring = "today, I love go out , , , ," (less than five commas and spaces)
mystring.Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",")
temp = temp.TrimEnd()
this trims the trailing spaces from a string.