Question Insert spaces into a string

Joined
Nov 9, 2009
Messages
16
Programming Experience
Beginner
Greetings

Is there a way to take an integer, say 10, and convert that to 10 spaces? What I've got is a text field that the users enters a number. I then need to convert that number into spaces and insert those spaces into a string of text. I've found several places to convert text to an integer but not the other way around. I don't mind reading if someone could point me in the right direction it would be apreciated.

Thank you
 
Never mind I was able to figure it out:

Dim intNum As Integer
Dim sTemp As String = ""

intNum = Text2.Text
Do Until intNum = 0
sTemp = sTemp & Chr(32)
intNum = intNum - 1
Loop
 
You can use the Space function and just pass it a numeric value rather then itterating thru a loop. Also you should turn Option Strict & Option Explicit ON in your projects to force you to covert your values to there proper datatypes. You shouldnt just apply a text value from a textbox into a numeric datatype variable.

VB.NET:
[COLOR="Blue"]Dim [/COLOR]intSpaces [COLOR="blue"]As Integer[/COLOR] = 0
[COLOR="blue"]Dim [/COLOR]strResult [COLOR="blue"]As String [/COLOR]= [COLOR="DarkRed"]""[/COLOR]

[COLOR="blue"]If Integer[/COLOR].TryParse(TextBox1.Text, intSpaces) = [COLOR="blue"]True Then[/COLOR]
    strResult = Space(intSpaces)
[COLOR="blue"]Else[/COLOR]
    [COLOR="SeaGreen"]'Invalid entry coding here[/COLOR]
    MessageBox.Show([COLOR="DarkRed"]"Invalid entry"[/COLOR])
    [COLOR="Blue"]Exit Sub[/COLOR]
[COLOR="blue"]End If[/COLOR]

MessageBox.Show(strResult & [COLOR="darkred"]"Done"[/COLOR])
 
Last edited:
You can also use the String constructor to construct the string with a repeated Char:
Dim spaces As New String(" "c, 10)
 
Back
Top