30 Common String Operations in C# and VB.NET – Part I

Posted by: Suprotim Agarwal , on 8/18/2008, in Category WinForms & WinRT
Views: 171250
Abstract: In this article, I have compiled some common String operations that we encounter while working with the String class. In Part I, I have covered 15 common string operations. In the next article, I will continue this article and cover 15 more.
30 Common String Operations in C# and VB.NET – Part I
 
In this article, I have compiled some common String operations that we encounter while working with the String class. In Part I, I have covered 15 common string operations. In the next article, I will continue this article and cover 15 more.
Update: Part II of this series can be found over here 30 Common String Operations in C# and VB.NET – Part II
All the samples are based on two pre-declared string variables: strOriginal and strModified.
C#
    string strOriginal = "These functions will come handy";
    string strModified = String.Empty;
VB.NET
    Dim strOriginal As String = "These functions will come handy"
    Dim strModified As String = String.Empty
1. Iterate a String – You can use the ‘for’ loop or ‘foreach’ loop to iterate through a string. The ‘for’ loop gives you more flexibility over the iteration.
C#
    for (int i = 0; i < strOriginal.Length; i++)
    {
        MessageBox.Show(strOriginal[i].ToString());
    }
or
    foreach (char c in strOriginal)
    {
        MessageBox.Show(c.ToString());
    }
VB.NET
For i As Integer = 0 To strOriginal.Length - 1
            MessageBox.Show(strOriginal(i).ToString())
      Next i
Or
For Each c As Char In strOriginal
            MessageBox.Show(c.ToString())
Next c
2. Split a String – You can split strings using String.Split(). The method takes an array of chars, representing characters to be used as delimiters. In this example, we will be splitting the strOriginal string using ‘space’ as delimiter.
C#
    char[] delim = {' '};
    string[] strArr = strOriginal.Split(delim);
    foreach (string s in strArr)
    {
        MessageBox.Show(s);
    }
VB.NET
      Dim delim As Char() = {" "c}
      Dim strArr As String() = strOriginal.Split(delim)
      For Each s As String In strArr
            MessageBox.Show(s)
      Next s
3. Extract SubStrings from a String – The String.Substring() retrieves a substring from a string starting from a specified character position. You can also specify the length.
C#
    // only starting position specified
    strModified = strOriginal.Substring(25);
    MessageBox.Show(strModified);
 
    // starting position and length of string to be extracted specified
    strModified = strOriginal.Substring(20, 3);
    MessageBox.Show(strModified);
VB.NET
      ' only starting position specified
      strModified = strOriginal.Substring(25)
      MessageBox.Show(strModified)
 
      ' starting position and length of string to be extracted specified
      strModified = strOriginal.Substring(20, 3)
      MessageBox.Show(strModified)
4. Create a String array – There are different ways to create a Single Dimensional and Multi Dimensional String arrays. Let us explore some of them:
C#
    // Single Dimensional String Array
 
    string[] strArr = new string[3] { "string 1", "string 2", "string 3"};
    // Omit Size of Array
    string[] strArr1 = new string[] { "string 1", "string 2", "string 3" };
    // Omit new keyword
    string[] strArr2 = {"string 1", "string 2", "string 3"};
 
    // Multi Dimensional String Array
 
    string[,] strArr3 = new string[2, 2] { { "string 1", "string 2" }, { "string 3", "string 4" } };
    // Omit Size of Array
    string[,] strArr4 = new string[,] { { "string 1", "string 2" }, { "string 3", "string 4" } };
    // Omit new keyword
    string[,] strArr5 = { { "string 1", "string 2" }, { "string 3", "string 4" } };
 
VB.NET
     ' Single Dimensional String Array
 
      Dim strArr As String() = New String(2) { "string 1", "string 2", "string 3"}
      ' Omit Size of Array
      Dim strArr1 As String() = New String() { "string 1", "string 2", "string 3" }
      ' Omit new keyword
      Dim strArr2 As String() = {"string 1", "string 2", "string 3"}
 
      ' Multi Dimensional String Array
 
      Dim strArr3 As String(,) = New String(1, 1) { { "string 1", "string 2" }, { "string 3", "string 4" } }
      ' Omit Size of Array
      Dim strArr4 As String(,) = New String(, ) { { "string 1", "string 2" }, { "string 3", "string 4" } }
      ' Omit new keyword
      Dim strArr5 As String(,) = { { "string 1", "string 2" }, { "string 3", "string 4" } }
 
5. Reverse a String – One of the simplest ways to reverse a string is to use the StrReverse() function. To use it in C#, you need to add a reference to the Microsoft.VisualBasic dll.
C#
    string strModified = Microsoft.VisualBasic.Strings.StrReverse(strOriginal);
    MessageBox.Show(strModified); 
VB.NET
    Dim strModified As String = StrReverse(strOriginal)
      MsgBox(strModified)
6. Compare Two Strings – You can use the String.Compare() to compare two strings. The third parameter is a Boolean parameter that determines if the search is case sensitive(false) or not(true).
C#
    if ((string.Compare(strOriginal, strModified, false)) < 0)
    {
        MessageBox.Show("strOriginal is less than strOriginal1");
    }
    else if ((string.Compare(strOriginal, strModified, false)) > 0)
    {
        MessageBox.Show("strOriginal is more than strOriginal1");
    }
    else if ((string.Compare(strOriginal, strModified, false)) == 0)
    {
        MessageBox.Show("Both strings are equal");
    }
VB.NET
      If (String.Compare(strOriginal, strModified, False)) < 0 Then
            MessageBox.Show("strOriginal is less than strOriginal1")
      ElseIf (String.Compare(strOriginal, strModified, False)) > 0 Then
            MessageBox.Show("strOriginal is more than strOriginal1")
      ElseIf (String.Compare(strOriginal, strModified, False)) = 0 Then
            MessageBox.Show("Both strings are equal")
      End If
7. Convert a String to Byte[] (Byte Array) – The Encoding.GetBytes() encodes all the characters into a sequence of bytes. The method contains six overloads out of which we will be using the Encoding.GetBytes(String).
C#
byte[] b = Encoding.Unicode.GetBytes(strOriginal);
VB.NET
Dim b As Byte() = Encoding.Unicode.GetBytes(strOriginal)
Note: You can adopt different character encoding schemes (ASCII, Unicode etc.) based on your requirement.
8. Convert Byte[] to String – The Encoding.GetString() decodes a sequence of bytes into a string.
C#
    // Assuming you have a Byte Array byte[] b
    strModified = Encoding.Unicode.GetString(b);
VB.NET
      ' Assuming you have a Byte Array byte[] b
      strModified = Encoding.Unicode.GetString(b)
9. Convert a String to Char[](Char Array) – To convert a String to Char Array, use the String.ToCharArray() which copies the characters in the string to a Unicode character array.
C#
    char[] chArr = strOriginal.ToCharArray();
VB.NET
      Dim chArr As Char() = strOriginal.ToCharArray()
10. Convert a Char[] to String – A convenient way to convert a character array to string is to use the String constructor which accepts a character array
C#
    strModified = new String(chArr);
VB.NET
      strModified = New String(chArr)
11. Test if String is null or Zero Length – A simple way to test if a string is null or empty is to use the String.IsNullOrEmpty(string) which returns a Boolean value.
C#
     bool check = String.IsNullOrEmpty(strOriginal);
VB.NET
       Dim check As Boolean = String.IsNullOrEmpty(strOriginal)
Create a String of characters accepted from user -
12. Convert the Case of a String – The String class contains methods to convert a string to lower and upper cases. However, it lacks a method to convert a string to Proper Case/Title Case. Hence we will use the ‘TextInfo’ class to do the same.
C#
    System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
    System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;
    // Lower Case
    MessageBox.Show(textInfo.ToLower(strOriginal));
    // Upper Case
    MessageBox.Show(textInfo.ToUpper(strOriginal));
    // Proper Case
    MessageBox.Show(textInfo.ToTitleCase(strOriginal));
VB.NET
      Dim cultureInfo As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
      Dim textInfo As System.Globalization.TextInfo = cultureInfo.TextInfo
      ' Lower Case
      MessageBox.Show(textInfo.ToLower(strOriginal))
      ' Upper Case
      MessageBox.Show(textInfo.ToUpper(strOriginal))
      ' Proper Case
      MessageBox.Show(textInfo.ToTitleCase(strOriginal))
13. Count the occurrences of words in a String – You can adopt multiple ways to find the occurrence of a word in a string. One of them is to use the String.IndexOf() which is one of the ways of finding the occurrence of the word. In VB.NET, use String.InStr().
Another simple way is to use ‘Count’ property of the Regex.Matches() collection. However this method is slow. We will explore both these methods in the sample.
C#
    // Using IndexOf
     int strt = 0;
     int cnt = -1;
     int idx = -1;
     strOriginal = "She sells sea shells on the sea shore";
     string srchString = "sea";
     while (strt != -1)
     {
         strt = strOriginal.IndexOf(srchString, idx + 1);
         cnt += 1;
         idx = strt;
     }
     MessageBox.Show(srchString + " occurs " + cnt + " times");
 
 
    // Using Regular Expression
     System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(srchString);
    int count = rex.Matches(strOriginal).Count;
    MessageBox.Show(srchString + " occurs " + count + " times");
VB.NET
      ' Using IndexOf
       Dim strt As Integer = 0
       Dim cnt As Integer = -1
       Dim idx As Integer = -1
       strOriginal = "She sells sea shells on the sea shore"
       Dim srchString As String = "sea"
       Do While strt <> -1
             strt = strOriginal.IndexOf(srchString, idx + 1)
             cnt += 1
             idx = strt
       Loop
       MessageBox.Show(srchString & " occurs " & cnt & " times")
 
 
      ' Using Regular Expression
       Dim rex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(srchString)
      Dim count As Integer = rex.Matches(strOriginal).Count
      MessageBox.Show(srchString & " occurs " & count & " times")
 
14. Insert Characters inside a String – The String.Insert() inserts text at a specified index location of a string. You can insert either a character or a string at a given index location. For eg: We will insert a string “very” at index 26 in string strOriginal.
C#
    strModified = strOriginal.Insert(26, "very ");
    MessageBox.Show(strModified);
 
VB.NET
strModified = strOriginal.Insert(26, "very ")
MessageBox.Show(strModified)
15. Replace characters in a String – The String.Replace() removes characters from a string and replaces them with a new character or string.
C#
    strModified = strOriginal.Replace("come handy", "be useful");
    MessageBox.Show(strModified);
VB.NET
      strModified = strOriginal.Replace("come handy", "be useful")
      MessageBox.Show(strModified)
 
So those were 15 common string operations that we saw in this article. In the next article, we will explore some more string operations that are used commonly in projects. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 
What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by David on Monday, August 18, 2008 1:29 PM
In the examples for counting words using Regix, the MessageBox is using cnt, not count as the number of words.
Comment posted by Suprotim Agarwal on Monday, August 18, 2008 9:15 PM
David: Thanks. That was a typo that missed my editor's as well as my eyes!!
Comment posted by Tom on Thursday, August 21, 2008 10:48 AM
#13 Count the occurrences of words in a String can be on one line.

Int32 occurs = (srchString.Length - srchString.Replace(searchValue,"").Length) / searchValue.Length

Comment posted by Suprotim Agarwal on Thursday, August 21, 2008 9:15 PM
Tom: Thanks for the tip!!
Comment posted by James Curran on Monday, August 25, 2008 1:05 PM
@Tom
You COULD write it that way --- if your principle concern is "source code line count". Most people consider "source code maintainability" or even "run-time efficiency" more important.  (Although -- it surprised me as not being that bad at run-time speed: In my tests, 8.78 seconds (IndexOf) to 9.93 seconds (Replace) (13% slower) to 200 seconds (Regex - 2191% slower!))
Comment posted by James Curran on Monday, August 25, 2008 1:08 PM
As note for #2, the delim array to Split is a param parameter, so that it could be written as:
string[] strArr = strOriginal.Split(' ', ',');  // split on space or comma
Comment posted by Suprotim Agarwal on Tuesday, August 26, 2008 5:06 AM
James: I agree. I got the same results with Regex. Regex is the slowest here. Thanks for posting the test results.

What was the test data you used?
Comment posted by asp.net on Tuesday, August 26, 2008 1:56 PM
<a href="http://www.progblog.ru">asp.net</a>
Comment posted by James Curran on Wednesday, August 27, 2008 2:11 PM
I used the "She sells sea shells" test data from the example. I repeated all three in loops (probably about 1 million times) to get a figure large enough to trust.
Comment posted by Andy on Friday, September 5, 2008 2:37 PM
In the "She sells sea shells" test, it would never show 0 occurences, right?

In other words, change the srchString to "frank", you would still get 1 occurence.

The fix is to set the 'int idx = -1;' right above the while loop with the indexOf.
Comment posted by Suprotim Agarwal on Sunday, September 7, 2008 2:04 PM
Andy: Thanks for your comment. Isn't that how it is done in the sample? I apologize if I have not been able to understand the comment. Please explain it further with the entire snippet of code.
Comment posted by Jannemanrobinson on Monday, September 29, 2008 9:36 AM
@ Tom!
Be carefull there.
Int32 occurs = (srchString.Length - srchString.Replace(searchValue,"").Length) / searchValue.Length

Might not be accurate every time.

Try to use that code to search for the numer of times "foofoo" occurs in "foofoofoo".
The correct answer is: 2.  Your functionality returns: 1.

Contact via msdn forums C# if needed ;-)
Comment posted by deepak on Thursday, October 9, 2008 1:57 AM
dotnet curry
Comment posted by Martin Rosén-Lidholm on Sunday, November 30, 2008 3:25 PM
I'm not very fond of using the VB library in C# as shown in the reverse example.

Rather, I'd implement a reverse method as an extension method for string. Also, in order to avoid dependency to the VB assembly, I'd probably use an implementation like so:

char[] strOriginalAsCharArray = strOriginal.ToCharArray();
Array.Reverse(strOriginalAsCharArray);
string strReversed = new string(strOriginalAsCharArray);

Regards,
/Martin R-L
Comment posted by hd on Tuesday, June 30, 2009 4:46 AM
good..nice one.
Comment posted by Carol on Thursday, July 7, 2011 2:37 PM
How would I trim a string, from another string?  (Not trying to trim whitespace or single characters)

Why doesn't this work:
s = "CatCatDogCatCatCat"
t = "Cat"
s = s.Trim(t)   ' Remove all leading and trailing "Cat"s
Comment posted by SusanSs on Sunday, March 2, 2014 9:07 PM
How would I only replace the Nth occurrence of a string inside another string?
Comment posted by Rajan on Monday, March 24, 2014 4:18 AM
It id very useful.

Thanks.
Rajan
Comment posted by sagar on Friday, March 28, 2014 2:41 AM
please help me my string is this
i want to get only "Your name" in the text box n edit the text box to replace this keyword please help me

"<text transform="translate(1 21) translate(10 3)" xml:space="preserve" text-anchor="left" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_1" y="26.5" x="49.5" stroke-width="0" stroke="#000" fill="#000000">your name</text>"
Comment posted by PaulaP on Thursday, October 30, 2014 2:55 PM
How would I replace characters in a string, based on their POSITION?

Insert the word "dog" in this string... at positions 15,16,17... overwriting
the characters that were already there.
Comment posted by ram on Friday, January 2, 2015 3:09 AM
How would I replace characters in a string, based on their POSITION?

Insert the word "dog" in this string... at positions 15,16,17... overwriting
the characters that were already there.

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook