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

Posted by: Suprotim Agarwal , on 8/20/2008, in Category WinForms & WinRT
Views: 284274
Abstract: In the previous article, 30 Common String Operations in C# and VB.NET – Part I, we explored 15 common String operations while working with the String class. In Part II of the article, we will continue with the series and cover 15 more.
30 Common String Operations in C# and VB.NET – Part II
In the previous article, 30 Common String Operations in C# and VB.NET – Part I, we explored 15 common String operations while working with the String class. In Part II of the article, we will continue with the series and cover 15 more.
All the samples are based on two pre-declared string variables: strOriginal and strModified.
    string strOriginal = "These functions will come handy";
    string strModified = String.Empty;
    Dim strOriginal As String = "These functions will come handy"
    Dim strModified As String = String.Empty
16. Count Words and Characters In a String – You can use Regular Expression to do so as shown below:
    // Count words
    System.Text.RegularExpressions.MatchCollection wordColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @"[\S]+");
    // Count characters. White space is treated as a character
    System.Text.RegularExpressions.MatchCollection charColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @".");
      ' Count words
      Dim wordColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, "[\S]+")
      ' Count characters. White space is treated as a character
      Dim charColl As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(strOriginal, ".")
17. Remove characters in a String - The String.Remove() deletes a specified number of characters beginning at a given location within a string
    // Removes everything beginning at index 25
    strModified = strOriginal.Remove(25);
    // Removes specified number of characters(five) starting at index 20
    strModified = strOriginal.Remove(20,5);
      ' Removes everything beginning at index 25
      strModified = strOriginal.Remove(25)
      ' Removes specified number of characters(five) starting at index 20
      strModified = strOriginal.Remove(20,5)
18. Create Date and Time from String – Use the DateTime.Parse() to convert a string representing datetime to its DateTime equivalent. The DateTime.Parse() provides flexibility in terms of adapting strings in various formats.
    strOriginal = "8/20/2008";
    DateTime dt = DateTime.Parse(strOriginal);
      strOriginal = "8/20/2008"
      Dim dt As DateTime = DateTime.Parse(strOriginal)
19. Convert String to Base64 - You will have to use the methods in System.Text.Encoding to convert string to Base64. The conversion involves two processes:
a.    Convert string to a byte array
b.    Use the Convert.ToBase64String() method to convert the byte array to a Base64 string
    byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);
    // convert the byte array to a Base64 string
    strModified = Convert.ToBase64String(byt);
      Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)
      ' convert the byte array to a Base64 string
      strModified = Convert.ToBase64String(byt)
20. Convert Base64 string to Original String - In the previous example, we converted a string ‘strOriginal’ to Base64 string ‘strModified’. In order to convert a Base64 string back to the original string, use FromBase64String(). The conversion involves two processes:
a.   The FromBase64String() converts the string to a byte array
b.   Use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();
    byte[] b = Convert.FromBase64String(strModified);
    strOriginal = System.Text.Encoding.UTF8.GetString(b);
      Dim b As Byte() = Convert.FromBase64String(strModified)
      strOriginal = System.Text.Encoding.UTF8.GetString(b)
21. How to Copy a String – A simple way to copy a string to another is to use the String.Copy(). It works similar to assigning a string to another using the ‘=’ operator.
    strModified = String.Copy(strOriginal);
      strModified = String.Copy(strOriginal)
22. Trimming a String – The String.Trim() provides two overloads to remove leading and trailing spaces as well as to remove any unwanted character. Here’s a sample demonstrating the two overloads. Apart from trimming the string, it also removes the "#" character.
    strOriginal = " Some new string we test ##";
    strModified = strOriginal.Trim().Trim(char.Parse("#"));
      strOriginal = " Some new string we test ##"
      strModified = strOriginal.Trim().Trim(Char.Parse("#"))
23. Padding a String – The String.PadLeft() or PadRight() pads the string with a character for a given length. The following sample pads the string on the left with 3 *(stars). If nothing is specified, it adds spaces.
    strModified = strOriginal.PadLeft(34,'*');
      strModified = strOriginal.PadLeft(34,"*"c)
24. Create a Delimited String – To create a delimited string out of a string array, use the String.Join()
    string[] strArr = new string[3] { "str1", "str2", "str3"};
    string strModified = string.Join(";", strArr);
      Dim strArr As String() = New String(2) { "str1", "str2", "str3"}
      Dim strModified As String = String.Join(";", strArr)
25. Convert String To Integer - In order to convert string to integer, use the Int32.Parse(). The Parse method converts the string representation of a number to its 32-bit signed integer equivalent. If the string contains non-numeric values, it throws an error.
Similarly, you can also convert string to other types using Boolean.Parse(), Double.Parse(), char.Parse() and so on.
    strOriginal = "12345";
    int temp = Int32.Parse(strOriginal);
      strOriginal = "12345"
      Dim temp As Integer = Int32.Parse(strOriginal)
26. Search a String – You can use IndexOf, LastIndexOf, StartsWith, and EndsWith to search a string.
27. Concatenate multiple Strings – To concatenate string variables, you can use the ‘+’ or ‘+=’ operators. You can also use the String.Concat() or String.Format().
    strModified = strOriginal + "12345";
    strModified = String.Concat(strOriginal, "abcd");
    strModified = String.Format("{0}{1}", strOriginal, "xyz");
      strModified = strOriginal & "12345"
      strModified = String.Concat(strOriginal, "abcd")
      strModified = String.Format("{0}{1}", strOriginal, "xyz")
However, when performance is important, you should always use the StringBuilder class to concatenate strings.
28. Format a String – The String.Format() enables the string’s content to be determined dynamically at runtime. It accepts placeholders in braces {} whose content is replaced dynamically at runtime as shown below:
    strModified = String.Format("{0} - is the original string",strOriginal);
      strModified = String.Format("{0} - is the original string",strOriginal)
The String.Format() contains 5 overloads which can be studied over here
29. Determine If String Contains Numeric value – To determine if a String contains numeric value, use the Int32.TryParse() method. If the operation is successful, true is returned, else the operation returns a false.
    int i = 0;
    strOriginal = "234abc";
    bool b = Int32.TryParse(strOriginal, out i);
      Dim i As Integer = 0
      strOriginal = "234abc"
      Dim b As Boolean = Int32.TryParse(strOriginal, i)
Note: TryParse also returns false if the numeric value is too large for the type that’s receiving the result.
30. Determine if a String instance starts with a specific string – Use the StartsWith() to determine whether the beginning of a string matches some specified string. The method contains 3 overloads which also contains options to ignore case while checking the string.
    if (strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase))
      If strOriginal.StartsWith("THese",StringComparison.CurrentCultureIgnoreCase) Then
      End If
So those were some 30 common string operations that we saw in these two articles. Since these articles contained only a short introduction of each method, I would suggest you to explore each method in detail using the MSDN documentation. Mastering string operations can save us a lot of time in projects and improve application performance too. I hope this article was useful and I thank you for viewing it.
 If you liked the article,  Subscribe to my RSS Feed. 
Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the pre-order of The Absolutely Awesome Book on C# and .NET. This is a concise technical eBook and will be available in PDF, ePub, and mobi.

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core. Use these concepts in your next .NET Project or to crack your next .NET Interview.

Click here to Pre-Order this eBook at a Discounted Price!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

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 Ger Rietman on Thursday, August 21, 2008 8:36 AM
To determine if a string contains a numeric value you could also use the IsNumeric function, e.g. as follows:

        Dim s As String = "123abc"
        If Not IsNumeric(s) Then
            MessageBox.Show("Input is not a number")
        End If

Comment posted by Suprotim Agarwal on Thursday, August 21, 2008 9:24 PM
Ger: Yes, IsNumeric is also a good way to do so.
Comment posted by Nishant on Sunday, August 24, 2008 11:37 AM
   I read ur articles
it is pretty good for freshers as well as developers.
i am trying to prepare for microsoft certification bt i m confused for what will be doing first either MCTS or MCP?
plz suggest me for that & send the guidelines for preparing the exams.
Comment posted by Suprotim Agarwal on Tuesday, August 26, 2008 5:15 AM
Nishant: When you clear a MS exam, you become an MCP first.

Did you check this link: http://www.microsoft.com/learning/mcpexams/faq/default.mspx
Comment posted by Nishant on Wednesday, August 27, 2008 11:47 AM
Thanks for reply Sir.
I will check it.
Comment posted by Muneeb Usman on Sunday, September 14, 2008 11:09 AM
Initially i was looking for string functions. your article is really good.
Comment posted by ss on Tuesday, October 7, 2008 11:50 PM
thx alot this's so good!
Comment posted by Visual C# Kicks on Monday, November 3, 2008 3:18 PM
Very good string functions. If anyone is interested in some more:

Comment posted by mamor on Friday, April 17, 2009 9:06 AM
very goog string methods . i asks about windows application .i am write security project where i read alphabatic string and need to convert it to integer value or its ASCII code but i can't . please any one answer me
Comment posted by John on Monday, October 5, 2009 11:42 AM
The Base64 to and from are super useful, good work on that.
Comment posted by Max on Saturday, March 27, 2010 3:46 AM
nr 16 - count all characters
why do you use a reg ex?
this would be many times faster:
Comment posted by Deepthi Vandana on Friday, September 30, 2011 2:19 AM
Hi Suprotim,

I am working with testing a website, i need to send the masked password **** as input. Could you help me how i could do it using C#.

Comment posted by Carol on Friday, December 2, 2011 10:34 AM
How would I trim a *WORD*, not a character, from string?

"Dog cat Dog catcatcat"

Trim 3 (or more) "cats" from the end.
Comment posted by d.naveen2012 on Sunday, December 11, 2011 5:53 AM
yah it's very helpfull...........
Comment posted by Robbage on Saturday, April 20, 2013 10:49 PM
Item 18 (dates from strings) won't work for different regions unless you use the year/month/day format (eg "2008/8/20") Otherwise: is "2/8/2001" the second of August or the eighth of January? In most of the world it is August.
Comment posted by Matt Taylor on Friday, June 28, 2013 1:32 PM
I want to have a long string of say 10 words and count x # of character after a certain word.

So if I have "The man jumped down" as my string...I would like to find out the next 6 characters after "man ". So the result would be "jumped".
Comment posted by Carol on Wednesday, September 18, 2013 8:07 PM
How would I make a string with copies of another string?

s = Copies("dog", 33)
Comment posted by José on Sunday, January 19, 2014 9:49 PM
Tengo este error cuando necesito pasar el contenido de un campo de una tabla a otra. Este error es tiempo de ejecución después de compilado. En tiempo de ejecución sin compilar funciona bien.

FormatException: Input string was not in a correct format.]
   Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat) +181
   Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) +60

dReg("ItemEval") = myRow.Item("ItemEval")

Trabajo en visual studio .net 2010 (asp.net *.aspx con vb *.aspx.vb)
Comment posted by sagar on Friday, March 28, 2014 2:54 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 Anitha on Tuesday, August 26, 2014 6:29 AM
Comment posted by Anitha on Tuesday, August 26, 2014 6:31 AM
how to declare a matchcollection in c#.net?





C# Book for Building Concepts and Interviews



jQuery CookBook