int num3 = int.Parse(str2,
System.Globalization.NumberStyles.AllowThousands);
Console.WriteLine(num3); //---9876---
Here is another example:
string str3 = "1,239,876";
num3 = int.Parse(str3,
System.Globalization.NumberStyles.AllowThousands);
Console.WriteLine(num3); //---1239876---
What about the reverse — formatting a number with the comma separator? Here is the solution:
num3 = 9876;
Console.WriteLine("{0:#,0}", num3); //---9,876---
num3 = 1239876;
Console.WriteLine("{0:#,0}", num3); //---1,239,876---
Last, to format a special number (such as a phone number), use the following format specifier:
long phoneNumber = 1234567890;
Console.WriteLine("{0:###-###-####}", phoneNumber); //---123-456-7890---
Earlier in this chapter you saw how to easily concatenate two strings by using the +
operator. That's fine if you are concatenating a small number of strings, but it is not recommended for large numbers of strings. The reason is that String
objects in .NET are immutable , which means that once a string variable is initialized, its value cannot be changed. When you concatenate another string to an existing one, you actually discard its old value and create a new string object containing the result of the concatenation. When you repeat this process several times, you incur a performance penalty as new temporary objects are created and old objects discarded.
One important application of the StringBuilder
class is its use in .NET interop with native C/C++ APIs that take string arguments and modify strings. One example of this is the Windows API function GetWindowText()
. This function has a second argument that takes a TCHAR*
parameter. To use this function from .NET code, you would need to pass a StringBuilder
object as this argument.
Consider the following example, where you concatenate all the numbers from 0 to 9999:
int counter = 9999;
string s = string.Empty;
for (int i = 0; i <= counter; i++) {
s += i.ToString();
}
Console.WriteLine(s);
At first glance, the code looks innocent enough. But let's use the Stopwatch
object to time the operation. Modify the code as shown here:
int counter = 9999;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
string s = string.Empty;
for (int i = 0; i <= counter; i++) {
s += i.ToString();
}
sw.Stop();
Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);
Console.WriteLine(s);
On average, it took about 374 ms on my computer to run this operation. Let's now use the StringBuilder
class in .NET to perform the string concatenation, using its Append()
method:
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= 9999; i++) {
sb.Append(i.ToString());
}
sw.Stop();
Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);
Console.WriteLine(sb.ToString());
On average, it took about 6 ms on my computer to perform this operation. As you can deduce, the improvement is drastic — 98% ((374-6)/374). If you increase the value of the loop variant (counter), you will find that the improvement is even more dramatic.
The StringBuilder
class represents a mutable string of characters. Its behavior is like the String
object except that its value can be modified once it has been created.
The StringBuilder
class contains some other important methods, which are described in the following table.
Method |
Description |
Append |
Appends the string representation of a specified object to the end of this instance. |
AppendFormat |
Appends a formatted string, which contains zero or more format specifiers, to this instance. Each format specification is replaced by the string representation of a corresponding object argument. |
AppendLine |
Appends the default line terminator, or a copy of a specified string and the default line terminator, to the end of this instance. |
CopyTo |
Copies the characters from a specified segment of this instance to a specified segment of a destination Char array. |
Insert |
Inserts the string representation of a specified object into this instance at a specified character position. |
Remove |
Removes the specified range of characters from this instance. |
Replace |
Replaces all occurrences of a specified character or string in this instance with another specified character or string. |
ToString |
Converts the value of a StringBuilder to a String . |
When dealing with strings, you often need to perform checks on them to see if they match certain patterns. For example, if your application requires the user to enter an email address so that you can send them a confirmation email later on, it is important to at least verify that the user has entered a correctly formatted email address. To perform the checking, you can use the techniques that you have learnt earlier in this chapter by manually looking for specific patterns in the email address. However, this is a tedious and mundane task.
A better approach would be to use regular expressions — a language for describing and manipulating text. Using regular expressions, you can define the patterns of a text and match it against a string. In the .NET Framework, the System.Text.RegularExpressions
namespace contains the RegEx
class for manipulating regular expressions.
To use the RegEx
class, first you need to import the System.Text.RegularExpressions
namespace:
using System.Text.RegularExpressions;
The following statements shows how you can create an instance of the RegEx class, specify the pattern to search for, and match it against a string:
string s = "This is a string";
Regex r = new Regex("string");
if (r.IsMatch(s)) {
Console.WriteLine("Matches.");
}
In this example, the Regex
class takes in a string constructor, which is the pattern you are searching for. In this case, you are searching for the word "string" and it is matched against the s string variable. The IsMatch()
method returns True
if there is a match (that is, the string s contains the word "string").
To find the exact position of the text "string" in the variable, you can use the Match()
method of the RegEx
class. It returns a Match
object that you can use to get the position of the text that matches the search pattern using the Index property:
Читать дальше