RickTicky
RickTicky

Reputation: 114

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. 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

Upvotes: 3

Views: 207

Answers (2)

user3972104
user3972104

Reputation:

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

Upvotes: 1

Ian
Ian

Reputation: 1251

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

If LetterToConvert = " " Then ....

Upvotes: 2

Related Questions