Tutorials Forums
     Tutorials Videos
        Sign Up Now For FREE
Welcome, Guest
Username Password: Remember me

String Operations in C# (Part II)
(1 viewing) (1) Guest
A programming language that evolved in part from Microsoft C++, C# was designed for building enterprise-level applications that run on the .NET Framework. C# is simple, modern, type safe, and object oriented. Whether you’re new to the language or an old pro, you’ll find articles in this section that will help you get your projects done.
  • Page:
  • 1

TOPIC: String Operations in C# (Part II)

String Operations in C# (Part II) 03 May 2010 16:02 #370

Introduction
In the previous article, 30 Common String Operations in C# (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;

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]+");
MessageBox.Show(wordColl.Count.ToString());
// Count characters. White space is treated as a character
System.Text.RegularExpressions.MatchCollection charColl = System.Text.RegularExpressions.Regex.Matches(strOriginal, @".");
MessageBox.Show(charColl.Count.ToString());

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);
MessageBox.Show(strModified);
or
// Removes specified number of characters(five) starting at index 20
strModified = strOriginal.Remove(20,5);
MessageBox.Show(strModified);

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 = "03/05/2010";
DateTime dt = 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);

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);

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);

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("#"));

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,'*');

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);

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);

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");

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);

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);

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))
MessageBox.Show("true");


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.

This attachment is hidden for guests. Please log in or register to see it.
Attachments:
  • Attachment This attachment is hidden for guests. Please log in or register to see it.
  • CE
  • OFFLINE
  • Administrator
  • Posts: 197
  • Karma: 78
CodersEngine
  • Page:
  • 1
Moderators: mnjon
Time to create page: 1.41 seconds