[Beginner-Friendly] [VB.NET] String Manipulation Snippets Vault [30 Operations] 04-14-2014, 03:57 PM
#1
So, let's start with a short introduction to what a string is.
In programming, a string is defined as data type that can represent a text, which is consisted from a collection of characters that contains spaces and numerical values as well. Unlike the "Integer" declaration, which can only contain a single numerical value.
Here are different methods of declaring a string:
NOTES:
- The separator after #25 means I'm advancing into the details.
- Dear guests, benefit from the code. Don't ripoff.
- Last thread update: 15/4/2014
1. Replace Function - creates changes in the contents of the string
2. Calculate String Length - calculates how many characters are in the string
3. Reverse String - creates a mirrored text
4. Construct a String - creates a string from a sequence of characters
5. ToUpper - converts all lowercase characters to uppercase characters
6. ToLower - converts all uppercase characters to lowercase characters
7. ToSentence - capitalizes first character and every first character after ".", "?", "!"
8. ToInverted - creates a mixture of uppercase and lowercase characters
9. Split Strings - creates a new line after each word
10. Join Strings - joins splitted strings and creates a sentence
11. Join Strings Without Using String.Join - concatenate strings and creates a sentence
12. String.Contains - checks if string contains the specified word
13. String.StartsWith - checks if string starts with the specified word
14. String.EndsWith - checks if string ends with the specified word
15. String.Trim - deletes leading and trailing instances of the specified character
16. String.LTrim - deletes empty spaces (nullspace) at the beginning of the string
17. String.RTrim - deletes empty spaces (nullspace) at the end of the string
18. Trim Punctuation - deletes punctuation characters, such as "!","?", "*", etc.
19. Count Words in String with RegEx - counts how many words are in the string
20. Count Chars in String with RegEx - counts how many characters are in the string
21. Delimited String - Adds a delimiter in the array of strings
22. Space To Tab - converts spaces to tabs
23. Tab To Space- converts tabs to spaces
24. Space To NewLine - converts spaces to new lines
25. EOL To Space - converts End of Line to sapce
26. ASCII To HEX - converts normal text to Hex
27. HEX To ASCII - converts Hex to normal text
28. ASCII To Base64 - converts normal text to Base64
29. Base64 To ASCII - converts Base64 to normal text
30. ASCII To ROT13 and Vice Versa - encrypts to/or decrypts from ROT13
In programming, a string is defined as data type that can represent a text, which is consisted from a collection of characters that contains spaces and numerical values as well. Unlike the "Integer" declaration, which can only contain a single numerical value.
Here are different methods of declaring a string:
Code:
'Declare without initializing.
Dim MyString As String
'Initialize to null.
Dim MyString As String = Nothing
'Declare with a regular string literal
Dim MyString As String = "Hello, world!"NOTES:
- The separator after #25 means I'm advancing into the details.
- Dear guests, benefit from the code. Don't ripoff.
- Last thread update: 15/4/2014
1. Replace Function - creates changes in the contents of the string
Code:
Dim Original As String = "The world is awful"
Dim Modified As String = Original.Replace("awful", "beautiful")
MsgBox(Modified)2. Calculate String Length - calculates how many characters are in the string
Code:
Dim Word As String = "Hello"
Dim Wordlength As Integer = Word.Length
MsgBox(Wordlength) 'Output should be 53. Reverse String - creates a mirrored text
Code:
Function ReverseString(ByVal value As String) As String
Dim chr() As Char = value.ToCharArray()
Array.Reverse(chr)
Return New String(chr)
End Function
'Usage:
Dim MyString As String = "Hello, world"
Dim ReversedString As String = ReverseString(MyString)
MsgBox(ReversedString)4. Construct a String - creates a string from a sequence of characters
Code:
Dim Letters As Char() = {"A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c}
Dim Alphabet As New String(Letters)
MsgBox(letters)5. ToUpper - converts all lowercase characters to uppercase characters
Code:
Dim MyString As String = "hello, world"
MyString = MyString.ToUpper()
MsgBox(MyString)6. ToLower - converts all uppercase characters to lowercase characters
Code:
Dim MyString As String = "HELLO, WORLD"
MyString = MyString.ToLower()
MsgBox(MyString)7. ToSentence - capitalizes first character and every first character after ".", "?", "!"
Code:
Public Function SentenceCase(ByVal MyString() As Char) As String
Dim sentenceStart As Boolean = True
Dim I As Integer
MyString = CStr(MyString).ToLower
For I = 0 To Len(MyString) - 1
If sentenceStart Then MyString(I) = CStr(MyString(I)).ToUpper
If MyString(I) <> " " Then sentenceStart = InStr(".!?", MyString(I))
Next
Return MyString
End Function
'Usage:
Dim MyString As String = "hello! this is Toxin. how are you?"
Dim ModifiedString As String = SentenceCase(MyString)
MsgBox(ModifiedString)8. ToInverted - creates a mixture of uppercase and lowercase characters
Code:
Private Function ToInverted(ByVal MyString As String) As String
Dim sResult As String = ""
Dim sChar As String = ""
Dim i As Integer
Dim capital As Boolean = True
For i = 0 To MyString.Length - 1
capital = Not capital
sChar = MyString.Substring(i, 1)
If capital Then
sResult &= sChar.ToUpper
Else
sResult &= sChar.ToLower
End If
Next
Return sResult
End Function
'Usage:
Dim MyString As String = "hello! this is Toxin. how are you?"
Dim ModifiedString As String = ToInverted(MyString)
MsgBox(ModifiedString)9. Split Strings - creates a new line after each word
Code:
Dim MyString As String = "i use sinisterly"
Dim SplittedString As String() = MyString.Split(New Char() {" "c})
Dim word As String
For Each word In SplittedString
MsgBox(word)
Next10. Join Strings - joins splitted strings and creates a sentence
Code:
Dim StringArray(3) As String
StringArray(0) = "sinisterly"
StringArray(1) = "is"
StringArray(2) = "really"
StringArray(3) = "nice"
Dim JoinedString As String = String.Join(" ", StringArray)
MsgBox(JoinedString)11. Join Strings Without Using String.Join - concatenate strings and creates a sentence
Code:
Dim MyString1 As String = "The forums of Sinisterly "
Dim MyString2 As String = "are full of joy"
Dim CompleteString As String
CompleteString = MyString1 + MyString2
MsgBox(CompleteString)12. String.Contains - checks if string contains the specified word
Code:
Dim MyString As String = "hello everyone"
If MyString.Contains("Hello") Then
MsgBox("true")
Else
MsgBox("false")
End If13. String.StartsWith - checks if string starts with the specified word
Code:
Dim MyString As String = "Sinisterly is awesome"
If MyString.StartsWith("Sinisterly", StringComparison.OrdinalIgnoreCase) Then
MsgBox("true")
Else
MsgBox("false")
End If
'NOTE:
' "StringComparison.OrdinalIgnoreCase" ignores the character case wether it's upper or lower14. String.EndsWith - checks if string ends with the specified word
Code:
Dim MyString As String = "Sinisterly is awesome"
If MyString.EndsWith("awesome", StringComparison.OrdinalIgnoreCase) Then
MsgBox("true")
Else
MsgBox("false")
End If
'NOTE:
' "StringComparison.OrdinalIgnoreCase" ignores the character case wether it's upper or lower15. String.Trim - deletes leading and trailing instances of the specified character
Code:
Dim MyString As String = "%%No Percentage%%"
Dim TrimmedString As String = MyString.Trim("%")
MsgBox(TrimmedString)16. String.LTrim - deletes empty spaces (nullspace) at the beginning of the string
Code:
Dim MyString As String = " hello, world"
Dim TrimmedString As String = LTrim(MyString)
MsgBox(TrimmedString)17. String.RTrim - deletes empty spaces (nullspace) at the end of the string
Code:
Dim MyString As String = "hello, world "
Dim TrimmedString As String = RTrim(MyString)
MsgBox(TrimmedString)18. Trim Punctuation - deletes punctuation characters, such as "!","?", "*", etc.
Code:
Function TrimPunctuation(ByVal value As String)
'// This function is not written by me (Toxin)
' Count leading punctuation.
Dim removeFromStart As Integer = 0
For i As Integer = 0 To value.Length - 1 Step 1
If Char.IsPunctuation(value(i)) Then
removeFromStart += 1
Else
Exit For
End If
Next
' Count trailing punctuation.
Dim removeFromEnd As Integer = 0
For i As Integer = value.Length - 1 To 0 Step -1
If Char.IsPunctuation(value(i)) Then
removeFromEnd += 1
Else
Exit For
End If
Next
' Remove leading and trailing punctuation.
Return value.Substring(removeFromStart,value.Length - removeFromEnd - removeFromStart)
End Function
'Usage:
Dim values() As String = {"One?", "--two--", "...three!","four", "five*"}
For Each value As String In values
MsgBox(TrimPunctuation(value))
Next19. Count Words in String with RegEx - counts how many words are in the string
Code:
Dim MyString As String = "These are four words"
Dim CoutWords As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(MyString, "[\S]+")
MessageBox.Show(CoutWords.Count.ToString())20. Count Chars in String with RegEx - counts how many characters are in the string
Code:
Dim MyString As String = "four"
Dim CountChars As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(MyString, ".")
MessageBox.Show(CountChars.Count.ToString())21. Delimited String - Adds a delimiter in the array of strings
Code:
Dim StringArray As String() = New String(2) {" 1 ", " 2 ", " 3 "}
Dim ModifiedString As String = String.Join("|", StringArray)
MsgBox(ModifiedString)22. Space To Tab - converts spaces to tabs
Code:
Dim MyString As String = "Sinisterly is nice"
Dim ModifiedString As String = MyString.Replace(" ", vbTab)
MsgBox(ModifiedString)23. Tab To Space- converts tabs to spaces
Code:
Dim MyString As String = "Sinisterly" & vbTab & "is" & vbTab & "nice"
Dim ModifiedString As String = MyString.Replace(vbTab, " ")
MsgBox(ModifiedString)24. Space To NewLine - converts spaces to new lines
Code:
Dim MyString As String = "Sinisterly is nice"
Dim ModifiedString As String = MyString.Replace(" ", ControlChars.Lf)
MsgBox(ModifiedString)25. EOL To Space - converts End of Line to sapce
Code:
Dim MyString As String = "Sinisterly" & vbLf & "is" & vbLf & "nice"
Dim ModifiedString As String = MyString.Replace(ControlChars.Lf, " ")
MsgBox(ModifiedString)![[Image: 09Wt2If.png]](http://i.imgur.com/09Wt2If.png)
26. ASCII To HEX - converts normal text to Hex
Code:
Dim MyString As String = "Sinisterly is nice".ToCharArray
Dim HexString As String
Dim sHex As String = ""
For Each ch As Char In MyString
sHex += Convert.ToString(Convert.ToInt32(ch), 16) & " "
Next
HexString = sHex
MsgBox(HexString)27. HEX To ASCII - converts Hex to normal text
Code:
Dim MyHexString As String = "53 69 6e 69 73 74 65 72 6c 79 20 69 73 20 6e 69 63 65"
Dim MyASCIIString As String
Dim arrStrings As String() = MyHexString.Trim(" "c).Split(" "c)
Dim sText As String = ""
For Each st As String In arrStrings
sText += Convert.ToChar(Convert.ToInt32(st, 16))
Next
MyASCIIString = sText
MsgBox(MyASCIIString)28. ASCII To Base64 - converts normal text to Base64
Code:
Dim MyString As String = "Sinisterly is nice"
Dim Base64String As String
Dim [Byte] As Byte() = System.Text.Encoding.UTF8.GetBytes(MyString)
Base64String = Convert.ToBase64String([Byte])
MsgBox(Base64String)29. Base64 To ASCII - converts Base64 to normal text
Code:
Dim MyBase64String As String = "U2luaXN0ZXJseSBpcyBuaWNl"
Dim MyASCIIString As String
Dim [Byte] As Byte() = Convert.FromBase64String(MyBase64String)
MyASCIIString = System.Text.Encoding.UTF8.GetString([Byte])
MsgBox(MyASCIIString)30. ASCII To ROT13 and Vice Versa - encrypts to/or decrypts from ROT13
Code:
'/ENC
Dim MyString As String = "Hello, world"
Dim EncOrDec As New StringBuilder
Dim CheckCharIndex As Integer
Dim CharIndex As Integer
For Each xChr As Char In MyString
If (Not Char.IsLetter(xChr)) Then
EncOrDec.Append(xChr)
Continue For
End If
CheckCharIndex = Asc("a") - (Char.IsUpper(xChr) * -32)
CharIndex = ((Asc(xChr) - CheckCharIndex) + 13) Mod 26
EncOrDec.Append(Chr(CharIndex + CheckCharIndex))
Next
MsgBox(EncOrDec.ToString())
'/DEC
Dim MyString As String = "Uryyb, jbeyq"
Dim EncOrDec As New StringBuilder
Dim CheckCharIndex As Integer
Dim CharIndex As Integer
For Each xChr As Char In MyString
If (Not Char.IsLetter(xChr)) Then
EncOrDec.Append(xChr)
Continue For
End If
CheckCharIndex = Asc("a") - (Char.IsUpper(xChr) * -32)
CharIndex = ((Asc(xChr) - CheckCharIndex) + 13) Mod 26
EncOrDec.Append(Chr(CharIndex + CheckCharIndex))
Next
MsgBox(EncOrDec.ToString())
![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)