PadLeft, PadRight
PadLeft, PadRight
The padding method either left or right aligns a String in its field and then pads the other end of the String
with spaces or a specified character to fill up the specified length of the field. The following code works for
both left and right padding of Strings:
Dim s1 As String = "Holy cow"
Dim dot As Char = Convert.ToChar(".")
Console.WriteLine(s1.PadLeft(20, dot)) 'or
Console.WriteLine(s1.PadRight(20, dot))
The output to the console is as follows:
Holy cow..........
............Holy cow
Note Observe the Convert.ToChar method used in the preceding code to change a character literal to a char
value. There is no character literal that forces conversion to type char.
Remove
Remove lets you remove a designated number of characters from a particular start index in a String. The
following code demonstrates this:
Dim s1 As String = "Holly cow"
Dim s2 As String = s1.Remove(3, 1)
Console.WriteLine(s2)
Replace
Replace lets you replace a character in a String with a new character. Consider the following code:
Dim str As String = "Holy cow"
Dim charc As Char = Convert.ToChar("w")
Dim charc1 As Char = Convert.ToChar("p")
str = str.Replace(charc, charc1)
Console.WriteLine(str)
The console output is as follows:
Holy cop
SubString
The SubString method lets you split a String into two Strings at the index location in the String and then
return the sub−String including the character at the index location. In the example provided, we want to
return just the sub−String and not the blank or space character at the location we obtain for the start of the
sub−String. The following code adds 1 to the location of the blank or space between the two words. We used
the IndexOf method to find the blank:
Dim str As String = "Holy cow"
Dim intI As Integer = str.LastIndexOf(" ")
str = str.SubString(int + 1)
Console.WriteLine(str)
503