转自:http://www.dotnetcurry.com/ShowArticle.aspx?ID=189
以下定义的二个字符串为例:
string strOriginal = "These functions will come handy"; string strModified = 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.
for (int i = 0; i < strOriginal.Length; i++) { MessageBox.Show(strOriginal[i].ToString()); } foreach (char c in strOriginal) { MessageBox.Show(c.ToString()); }
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.
char[] delim = {' '}; string[] strArr = strOriginal.Split(delim); foreach (string s in strArr) { MessageBox.Show(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.
// 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:
// 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" } };
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.
stringstrModified = Microsoft.VisualBasic.Strings.StrReverse(strOriginal);
MessageBox.Show(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).
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"); }
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).
byte[] b = Encoding.Unicode.GetBytes(strOriginal);
8. Convert Byte[] to String – The Encoding.GetString() decodes a sequence of bytes into a string.
// 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.
char[] chArr = 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
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.
bool check = String.IsNullOrEmpty(strOriginal);
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.
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));
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.
// 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");
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.
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.
strModified = strOriginal.Replace("come handy", "be useful"); MessageBox.Show(strModified);/Files/chenqingwei/30种字符串常用操作.rar