We explored 15 common string operations during working with the string class in the previous article 30 Common String Operations in C # and VB.NET, Part I. We will continue to cover the series in Part II of the article and 15 others.
The two previously declared string variables are the basis for all examples.
C#
string strOriginal = "These are string Examples";
string strModified = string.Empty;
VB.Net
Dim strOriginal As String = "These are string Examples"
Dim strModified As String = string.Empty
To count words and characters in string, we can use the following regular expression:
C#
// Count words
System.Text.RegularExpressions.MatchCollection wordCount = System.Text.RegularExpressions.Regex.Matches(strOriginal, @"[\S]+");
MessageBox.Show(wordCount.Count.ToString());
// Count characters. White space is treated as a character
System.Text.RegularExpressions.MatchCollection charCount = System.Text.RegularExpressions.Regex.Matches(strOriginal, @".");
MessageBox.Show(charCount.Count.ToString());
VB.Net
VB.NET
' Count words
Dim wordCount As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, "[\S]+")
MessageBox.Show(wordCount.Count.ToString())
' Count characters. White space is treated as a character
Dim charCount As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, ".")
MessageBox.Show(charCount.Count.ToString())
The Remove() function can delete a number of characters that start at a certain place in a string...
C#
// Removes everything beginning at index 25
strModified = strOriginal.Remove(25);
MessageBox.Show(strModified);
or
// Removes specified number of characters(five) starting at index 20
strModified = strOriginal.Remove(20,5);
MessageBox.Show(strModified);
VB.Net
' Removes everything beginning at index 09
strModified = strOriginal.Remove(05)
MessageBox.Show(strModified)
Or
' Removes specified number of characters(five) starting at index 09
strModified = strOriginal.Remove(9,5)
MessageBox.Show(strModified)
Use DateTime.Parse()
to convert a datetime string to its equivalent DateTime. DateTime.Parse()
offers flexibility in adapting strings in different formats.
C#
strOriginal = "25/05/2019";
DateTime dt = DateTime.Parse(strOriginal);
VB.Net
strOriginal = "25/05/2019"
Dim dt As DateTime = DateTime.Parse(strOriginal)
In System.Text.Encoding
we must use methods to transform string into Base64. Two processes involve the conversion:
C#
byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);
// convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt);
VB.Net
Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)
' convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt)
We converted the "strOriginal" string to the "strModified" string in the previous example. Use FromBase64String()
to convert a Base64 string back to the original string.
There are two processes involved in conversion:
Base64String()
, the string is converted into a byte array.UTF8.GetString();
C#
byte[] b = Convert.FromBase64String(strModified);
strOriginal = System.Text.Encoding.UTF8.GetString(b);
VB.Net
Dim b As Byte() = Convert.FromBase64String(strModified)
strOriginal = System.Text.Encoding.UTF8.GetString(b)
The Copy() method is a simple way to copy a string to another. It works the same way as the =
operator assigns a string to another.
C#
strModified = String.Copy(strOriginal);
VB.Net
strModified = String.Copy(strOriginal)
The .Trim()
provides two overload for removing lead and trailing spaces and for removing any undesirable characters. A sample of the two overloads is presented here. It also deletes the "#" character except for trimming the string.
C#
strOriginal = "Some new string we test ##";
strModified = strOriginal.Trim().Trim(char.Parse("#"));
VB.Net
strOriginal = " Some new string we test ##"
strModified = strOriginal.Trim().Trim(Char.Parse("#"))
The .PadLeft()
or .PadRight()
string is padded for a given length by a character. The next example pads with 3 * (stars) the string on the left. It adds spaces if nothing is specified.
C#
strModified = strOriginal.PadLeft(34,'*');
VB.Net
strModified = strOriginal.PadLeft(34,'*');
Use .Join()
to create a delimited string from a string array.
C#
string[] strArr = new string[3] { "str1", "str2", "str3"};
string strModified = string.Join(";", strArr);
VB.Net
Dim strArr As String() = New String(2) { "str1", "str2", "str3"}
Dim strModified As String = String.Join(";", strArr)
Use the Int32.Parse()
to convert string to integer. The Parse method converts a number string to its 32-bit integer equivalent. When non-numeric values are contained in the string, it throws an error.
Likewise, with Boolean.Parse()
, Double.Parse()
, char.Parse()
, and so on, you can also convert the string to other kinds.
C#
strOriginal = "12345";
int temp = Int32.Parse(strOriginal);
VB.Net
strOriginal = "12345"
Dim temp As Integer = Int32.Parse(strOriginal)
We can search for a string with IndexOf
, LastIndexOf
, StartsWith
, and EndsWith
.
We can use +
or + =
operators for combining string variables. The .Concat()
or the .Format()
can also be used.
C#
strModified = strOriginal + "12345";
strModified = String.Concat(strOriginal, "abcd");
strModified = String.Format("{0}{1}", strOriginal, "xyz");
VB.Net
strModified = strOriginal & "12345"
strModified = String.Concat(strOriginal, "abcd")
strModified = String.Format("{0}{1}", strOriginal, "xyz")
Note: When performance is important, we should always use the StringBuilder class to concatenate strings
The .Format()
method allows a dynamic determination of the content of the string.
It supports placeholders in braces { }
whose contents are dynamically replaced during operation as shown below:
C#
strModified = String.Format("{0} - is the original string",strOriginal);
VB.Net
strModified = String.Format("{0} - is the original string",strOriginal)
The .Format()
contains 5 overload, that you can study here.
Use the Int32.TryParse()
method to determine if the string has a numerical value or not.
C#
int i = 0;
strOriginal = "234abc";
bool b = Int32.TryParse(strOriginal, out i);
VB.Net
Dim i As Integer = 0
strOriginal = "234abc"
Dim b As Boolean = Int32.TryParse(strOriginal, i)
Remember: TryParse returns also false when the numeric value for the type receiving the result is too large.
To determine if the beginning of a string matches a certain specified string, use StartsWith()
. The procedure contains three overloads, which also include case ignore options during string checking.
C#
if (strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase))
MessageBox.Show("true");
VB.Net
If strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase) Then
MessageBox.Show("true")
End If
Since these articles only contained a brief introduction to each method, We suggest you use the MSDN documentation to explore each method detailedly. String mastering can save us time in projects and enhance application performance too.