My For Loop skips my IF statement

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. Therefore, "IT WAS" should look like this: 7384 876583 65

When I use the Step Into function in VB, I see that the for For loop is skipping my IF statement, which should give me my spaces. I do not understand why. As you can probably tell, I'm a beginner so any special 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
    txtAscii.Text = ConvertedLetter



source to share

2 answers

Because you are comparing PlainText, which is an entire string, to "". It should be:

If LetterToConvert = "" Then ....



Try the following:

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<>" "
        ConvertedLetter &= " " ' c is space means add a space
    End If
MsgBox(ConvertedLetter) ' display the result


You will get the result as

7384 876583 65



All Articles