Net runtime string

xiaoxiao2021-03-06  121

Most .NET languages ​​contain some built-in string support. For example, these languages ​​typically support string frequencies and such as concurrent operations. But the grammar used in various languages ​​is different.

String in C #

String value in C #

C # supports two string frequencies: "Regular" string common value and "check" string common value.

Regular string often is similar to the string of string in C and C : they are separated by quotation marks, which can contain escape sequences to represent various control characters and any Unicode characters. Their length cannot exceed a row, but can use the operator to set the adjacent string common value when compiling. All escape sequences begin with a backslash ("/"), as listed in the table below.

Table 1: C # string Fast-value escape sequence

Semiration sequence description

/ T tuper (unicode 0x0009).

/ r Enter (0x000D).

/ n New Row (Robes) (0x000A).

/ V Vertical Table (0x000B).

/ a alarm (0x0007).

/ B back (0x0008).

/ f converted page (0x000c).

/ 0 NULL (0x0000).

// The backslash (0x005c).

/ 'Single number (0x0027).

/ "Double quotes (0x0022).

/ XD variable bit number of hexadecimal code.

/ uAbcd Unicode character 0xAbcd (u or u can, where A, B, C, and D are effective hexadecimal bits 0-9, A-F and A-F).

These escape sequences (such as '/ t') can be included in any regular string common value or characteristic value. Further, the identifier may also include a Unicode escape sequence, so "if (A / U0066B == True)" "IF (AFB == True)" is the same (because Unicode 0x0066 is "F"). So, you can use any valid Unicode characters to write identifiers, even if the characters are not displayed on your keyboard or cannot be displayed in the editor.

The word string is based on @ ", which is the match to match the quotation marks. They do not include the escape sequence. So

@ "// Machine / Share / Path1 / Path2 / File.ext"

Equivalent to

"Machine // Share // Path1 // Path2 // File.ext"

But the former is much simpler and it is not easy to have errors. The length of the criterion string can also exceed one line. At this point, they will contain all space characters between quotation marks:

@ "First / t line

Tabbed Second Line "

/ / Is equivalent to "first // t line / r / n / ttabbed second line"

Note: Do you need "/ r" in the second string depends on the editor. Microsoft® Visual Studio® .NET uses ause / commission pair at the end of each row, so if you create a file using the Visual Studio .NET Editor, you need these two symbols. Other editors may only use a lobby to end the row (ASCII code 10 or newline).

The only exception to the "do not include the escape sequence" rule of the word string is, in the word string, use dual double quotes to represent a double quotation mark:

@ "This is a" "quote" "from me."

/ / Is equivalent to "this is a /" quote / "from me."

String operation in C #

C # language supports the following string operations: establish a string index to read (but not written) single characters, such as S [i].

Use the operator and set two strings, such as S T. S or T may not be a string, if one of the two is not a string, it will call toString to convert it into a string. Operators are part of the C # language, not members of the String class. If one of the operands is NULL (with empty strings ", it will be converted into an empty string. If this operation can be performed at compile time, execute it when compiling.

The equivalent is equal, such as s == T and S! = T. These operators are part of the String class, so they can be used in any language that supports overloaded operators. By using member name OP_EQUALITY and OP_INEQUALITY instead of operator syntax, they can be used even if the language of the overloaded operator is not supported (such as Microsoft® Visual Basic® .NET). These operators will call String.Equals, which compares the characters in the two strings, rather than the comparison of the distinction.

If possible, the parallel will be completed at compile time. You can also parallel any object with a string, thereby returning the value of the TOString method of the object. For example, all strings below are valid:

String S0 = "Hello";

String S1 = S0 5; // "Hello 5"

String S2 = 6.3 S1; // "6.3 Hello 5"

String Ret = string.format ("S0: {0} / NS1: {1} / ns2: {2}", S0, S1, S2);

In addition, due to the string of the string, the compiler and the repetition string are combined, such a copy contains only one copy of each string common value.

String in Visual Basic .NET

String Facts in Visual Basic .NET

Visual Basic .NET string is very simple: consists of a set of Unicode characters contained in double quotes. If you want to include double quotes in the string, you need to use double double quotes, such as:

"This prints" "Hello, World!" "On the screen"

Visual Basic .NET string Fast value or characteristic value does not exist of a synergistic sequence mechanism, but can contain double quotes. (This is similar to the C # check string of string, just Visual Basic .NET string Fast value cannot contain row characters, but can only be included on one line.) If necessary, it is necessary to include unrecovered characters in the Visual Basic .NET program. (If you change the line, you need to create this character with the CHR or Chrw function, then categorically with the string. Note that the use of the Enter (CHR (13)) can cause two rows to cover each other on the screen, because there is no wrap after the carriage return. If you need to use the Enter and the wrap, you can use the Environment.newline property:

"First Line" & chr (10) & "second line" 'only enters the car

"First Line" & Environment.newline & "Second Line" 'Enter and wrap string operation in Visual Basic .NET

Visual Basic .NET contains all C # string operators, including some operators in some C #. Visual Basic .NET operators include:

Use the operator to simply concurrent String and String, such as S T. This operator performs a string parallel when both operands are strings. If either operand is not a string, Visual Basic .NET will try to convert the string into Double and perform numeric additions. Therefore, it is preferred to perform parallel using & operators, as described below.

Use & operators and two objects, such as S & "There". If the number of operators are not a string, they will be converted into strings. That is, you can even set up a string of two numbers. For example, using the syntax X & Y and set the string of two numbers x and y. This operator is preferred when performing and set, because it is clear and always performs a parallel.

The following is all comparative operators: =, <>,>, <,> =, <=, these operators perform binary or text (distinctive environment) comparison, which comparison is executed depending on the compilation option and the OPTION COMPARE statement (if there ). You can use Strcomp to perform strings comparison by using the Option Compare to set the comparison type or pass the parameters.

Using the LIKE operator can determine if the string matches a pattern that is described using a simplified regular expression language. The regular expression language supported by System.Text.RegularExpressions.Regex has more features, so you may want to use the API.

Visual Basic .NET does not contain an index generator, so you cannot use the array subscript representation to access the individual characters in the string, but you can use the Chars attribute to get a single character of the string, and obtain each character of the StringBuilder.

Visual Basic .NET unique string function and statement

In addition to the operators provided by the Visual Basic .NET language, Visual Basic .NET also includes a function and statement of some unique operation strings, and the standard .NET Frame library does not contain these contents.

If you are a Visual Basic .NET programmer, you can choose to use the Visual Basic's unique version, or the standard .NET framework version. (However, in some respects, Visual Basic provides corresponding functions, and the .NET framework is not available.) DR. GUI strongly recommends that as long as it can, it will always adhere to the standard .NET framework API. This will improve your skills, and these skills can be applied to other languages ​​in the future.

On the other hand, if you want to migrate early Visual Basic code to Visual Basic .NET, use Visual Basic's unique version is quite convenient, because Visual Basic's own version of syntax and behavior are very similar to the syntax and behavior in the early Visual Basic. .

Substring

If you have been programmed with BASIC, you should remember the LEFTs, RIGHTs, and MID functions for extracting characters from the left side, right and intermediate of the string. You may even remember that the MID can be used on the left side of the assignment operator to change the characters in the string! These features are also included in Visual Basic .NET, just like you remember. One thing is important: the index at the start character in the MID starts from 1, not from 0 from 0 in other indexes in .NET. (This is because the MID $ in Basic is from 1, and the MID is inherited from the former.)

This is a very serious problem, Dr. GUI recommends never use MID in the new code. You can keep them in a normal running code that you want to migrate, but you have to make psychological preparations, and when debugging, you will be unable to endure between starting from 1 and starting from 0.

String.substring method provides overload function, which is a very good way to replace the LEFT and MID functions. For Left, just use str.substring (0, len); for MID, you can use str.substring (start, len), but remember to adjust a starting point because Substring's starting point points 0, while the starting point of MID It is directed to 1.

Right is slightly more complicated because the starting position must be calculated. E.g:

DIM S as string = "Hello, World!"

DIM T1 as string = s.substring (S.Length - Sublen)

'Same as the following statement

DIM T2 AS STRING = Right (S, SUBLEN)

Dim Ret as string = string.format ("s0: {0} / nt1: {1} / nt2: {2}", S, T1, T2)

Ret = ret.replace ("/ n", environment.newline)

Note that this Dr. GUI is using tips. Because Visual Basic .NET has no commission symbol sequence, he solves this problem by including the escape sequence ("/ n"), and then uses two characters to environment.newline string ("/" before returning a string. R / N ") Replace each escape sequence. If you want the output string and the string in the C # version, "/ N" should be replaced with CHR (10) (not Environment.newline).

Replace the MID statement (the character used to replace the string) is more complicated. You can use String.Remove to delete characters you want to replace and use string.insert into new characters, but do two new strings need to be created. We can choose a more effective way to create StringBuilder based on the first sub-string of the string to be modified, and then attach the replacement character to it, then add the tail of the original string, such as:

DIM S as string = "123456xxx0"

'Sub string starts from 0

DIM SB AS STRINGBUILDER = New StringBuilder (s.substring (0, 6))

SB.Append ("789")

Sb.Append (S.Substring (9, 1)) 'starting from 0 0 characters

S = sb.tostring () 'is the same as the MID (S, 7, 3) = "789" starting from 1

DIM T as string = "123456xxx0"

MID (T, 7, 3) = "789"

Dim Ret as string = string.format ("s: {0} / nt: {1}", s, t)

Ret = ret.replace ("/ n", environment.newline)

A very strange function

Visual Basic .NET contains a very strange function, ie StrConv. It uses a set of bits to specify a variety of conversion methods, converting a string into another string. It uses the file system rules or the rules that distinguish the environment to convert cases (lower-write words, the first letter capitalization), and some conversions are only meaningful when you use the corresponding East Asian language (such as Japanese, Chinese or Korean). (Can be performed): Convert full / half angle, and the conversion slice fake name (Japanese only). Pressing the mutual conversion between Simplified Chinese and Traditional Chinese, but Dr. GUI knows that this function is not good, so it is not recommended to use it.

For most such conversions, there is no corresponding function in the .NET Framework API. However, these conversions are done using the Windows LcmapString API; if you really want to convert with the .NET language (rather than Visual Basic), you can use the platform API interoperability to call lcmapstring (just like Visual Basic).

Function matching with .NET framework function

There are many Visual Basic .NET string functions match the .NET framework function. The following table lists the Visual Basic .NET function and its closest .NET framework. Please note that in some cases, the following features are not completely equivalent. In addition, pay attention to, in many cases, the .NET framework version has been overloaded to provide additional functions. You need to read the documentation in order to take full advantage of these features. You can use the following table to determine the appropriate way you want to see.

Table 2: Visual Basic's unique string function and its closest standard .NET framework

Visual Basic .NET function semantic closest .NET framework

Strreverse reversed strings. None - By switching the character position, use StringBuilder and looping.

Instr, Instrrev look up the first / last index of the substrings. Indexof, LastIndexof

LCASE, UCase converted to lowercase / uppercase. TOLOWER, TouPper

Format, FormatCurrency, FormatNumber, FormatPercent convert the value of the distinctive environment to a string representation. Obj.toString or String.Format

Str, VAL conversion between values ​​and strings, does not distinguish the environment. Any one of the above, specifying CultureInfo.invariant.

TRIM, LTRIM, RTRIM (Space only) Remove spaces between the strings. String.trim, string.trimstart, string.trimend (not only remove space, but also remove other characters.)

Len returns the length of the string. String.Length

Space, STRDUP creates a string using a duplicate space or other characters. Accept string constructor of characters and counts. Replace replaces the sub-string in the string. String or Replace in StringBuilder.

Split, Join disconnects the string at the specified separator to create a string array, or create a separated string from the string array. String.split, string.join

Filter creates another string array from an array containing a sub-string. Without equivalence, you need to write for-Each loops, which may need to put strings into dynamically extended ArrayList.

ASCW, CHRW is switched back and forth between Unicode integers and single-character strings. Conversion of char to integer type or the opposite.

ASC, CHR comes back and forth between code page integers and single-character strings. Use encoding (later).

CSTR is converted to a string. Obj.tostring

Use standard .NET framework API string

Create a String object

In both languages, you can create a String object using the new / new statement. Most String constructor compatible with the CLI can do not accept any parameters or accept one character and an integer, or accept one character array. So, unless you have a character array, you still need to use other methods to create a string. There is no constructor that can be accepted. However, there is a constructor accepting a char and an integer count, which creates a string that will contain a specified character that repeated the specified number of times.

The most common way is to initialize a string common value and use another string to assign it:

[C #]

String s = "Hello, World!";

String t = s; // does not copy; S and T reference the same string

String Ret = String.Format ("S and T Refer to Same: {0}",

Object.referenceequals (s, t));

[Visual Basic .NET]

DIM S as string = "Hello, World"

DIM T as string = s' does not copy; s and t reference the same string

DIM RET AS STRING = String.Format ("S and T Refer to Same: {0}", S IS T)

When will the cloning function does not perform clone?

Do you want two independent strings to contain the same value? Of course, you usually don't want this. Why waste memory? Moreover, because the string is not changeable, two separate strings having the same value have not much sense.

So, although String implements Iclonable, String.clone only returns a reference to the same string without cloning.

However, all functions are also: If you insist on having a second copy of the string, you can use the static method Copy. Please note that we will check the equivalence of references by two methods: the first method is to call Object.referenceequals, the second method is to convert the reference to Object before the test equivalence in the C #, or in Visual Basic Use the IS operator.

[C #]

String s = "hello";

String t = (string) s.clone (); // does not copy; s and t reference the same string

String u = string.copy (s); // Different object string Ret = string.format ("s Same as u: {0}, S Same AS U: {0}, S SAME AS U: {0}",

Object.referenceeequals (s, t), (object) s == (Object) u);

[Visual Basic .NET]

DIM S as string = "Hello"

DIM T as string = cstr (s.clone ()) 'does not copy; s and t reference the same string

DIM u AS String = String.copy (s) 'for copy, S and u reference two objects

DIM RET As String = String.Format ("s Same as u: {0}, s Same AS u: {1}", _

Object.referenceeequals (s, t), s u)

You can also use the String.copyTo method to copy all or some characters of a string to the character array. (Create a string according to the character array or part of the character array or part of the character array as a parameter.)

Other interfaces, properties and fields

As we understand, String has achieved iCloneable through a very strange but reasonable way. It also implements iComparable. That is to say, you can compare two strings using the iComparable CompareTo method (described below) compare two strings. Although String implements iConvertable, you should use the method in the Convert class to convert a string to a built-in value type using the TO ... Method.

String also has some interesting properties. You can know the length of any string (by a character count) by accessing the length of the string (read-only). Use index builder properties Chars (corresponding to C # index builder, read-only), can access one of the strings once.

[C #]

String s = "Hello, World!";

StringBuilder SB = New StringBuilder (String.Format)

"/" Hello, World! / "IS {0} / n", S.LENGTH)); // 13

For (int i = 0; i

Sb.appendformat ("{0}", s [i]);

[Visual Basic .NET]

DIM S as string = "Hello, World!"

DIM SB AS STRINGBUILDER = New StringBuilder (_

String.Format ("Length of" "Hello, World!" "IS {0}", s.ley ") '13

Sb.append (Environment.newline)

DIM I as integer

For i = 0 to S.LENGTH - 1

Sb.appendformat ("{0}", S.Chars (i))

NEXT

Please note that because the index of string characters starts from 0 (even in Visual Basic .NET), we should pay attention to correctly writing loops (in C #, the processing of this problem is to use

String equivalent / comparison method

Two strings can be compared by a number of methods. For the equivalent and not equivalent comparison, the main difference is of course, it is a comparison reference (two strings point to the same object) or the comparison value (two strings contain the same character).

Another main difference is that the other main difference is the use of the current environment, or use the original serial number value of each character in the string. (There is also a smaller difference, that is, whether it is case sensitive.) The default settings of the comparison are the current environment where they are located and are case sensitive. Usually, this setting is the settings you need.

== Operator calls String.Equals, the latter will perform a comparison of distinctive environments and case. If you want to use a C # comparison reference, you can convert two string references to Object, or use Object.Referenceequals. In Visual Basic .NET, you can use the IS operator (in Visual Basic) as follows, or use Object.Referenceeequals. Note that Object.referenceeequals can be used in both languages.

[C #]

String s = "hello", t = "there";

Bool valuecomp = (s == T); // value comparison

BOOL REFCOMP1 = ((Object) s == (Object) T); // Reference Comparison

Bool refcomp2 = Object.referenceequals (s, t); // Reference comparison

String Ret = string.format ("s == T: {0},"

"(Object) s == (Object) T: {1}, ObjectRefeq (S, T): {2}",

ValueComp, Refcomp1, Refcomp2;

[Visual Basic .NET]

DIM S as string = "Hello"

Dim t as string = "there"

DIM VALUECMP AS BOOLEAN = S = T 'value comparison

DIM REFCOMP1 AS BOOLEAN = S Is T 'reference comparison

Dim Refcomp2 as boolean = Object.referenceeequals (s, t) 'reference comparison

DIM RET As String = _

String.format ("s = t: {0}, s is t: {1}, obrefeq (s, t): {2}", _

ValueComp, Refcomp1, Refcomp2)

The equivalence of Visual Basic .NET (=, <>,>, <, <,> = and <=) can perform the serial number comparison, and the comparison of the distinction environment can also be performed, depending on the compiler option and Option COMPARE statement. To perform a reference comparison, use the IS operator. Visual Basic .NET also uses the LIKE operator to perform a string comparison, it can make a simple mode match. The Equals method has a variety of forms. There are two examples: a kind of accepting string as a parameter, another accepts Object (must reference a String). There is also a static version of Equals accepting two strings. Accept the version of Object is overwritten (originally defined in Object); the version of the version of the string is faster because there is no need to convert; and the static version can handle the passed NULL / NOTHING without exception.

Compares can be compared by three methods: Compare, Compareordinal, and Compareto. If the value of the first string is less than the value of the second string, it returns a negative number; if the value of the two strings is the same, it returns 0; if the value of the first string is greater than the second The value of a string is returned.

Compare is a set of heavy-duty static methods. By default, the comparison of distinct environments and case is performed. Each overload accepts at least two strings for comparison, and some overload accept Boolean (in specify case sensitive case) and INT32 (index and length of the sub-string to be compared, without comparing the entire string) .

Compareordinal is a pair of heavy-duty static methods for comparing the serial numbers of two strings or their sub-strings.

CompareTo is an instance method that implements iComparable. This method compares the current string with a string or object that is passed as a parameter, and distinguishes the environment and case in the comparison.

Search string: endswith / startswith / indexof / lastindexof / substring

You can find the content contained in the string through a variety of ways. If the current string starts / ends at the specified string, endswith and StartSwith will return true, otherwise returns false.

Both indexof and lastindexoes contain multiple overloads. Each overload returns the first / last position that appears in the current string (or character array) in the current string (or its sub-string).

SubString is similar to the previous GW-Basic MID $ function and the Visual Basic .NET MID function, just the index of the string starts from 0, and starting from 1 in MID / MID $. There are two overloads: one created and returned a new string, which contains a sub-string from the specified index to the end of the string. Another also creates and returns a new string, but contains a sub-string from the specified length starting at the specified index.

format

The String class has a series of static Format methods overload. All overloads provide formatting features, which is the same as those used when calling console.writeline. They create and return new strings, where the format indicator is replaced by a string of the remaining parameters. For example, you can use:

[C #]

String Ret = String.Format ("The value is {0}", 5);

// "Value 5" (no quotation marks)

[Visual Basic .NET]

DIM RET As String = String.Format ("The value is {0}", 5) '"value 5" (no quotation marks)

Other methods can also be used to determine the data format, but involve a number of problems that distinguish the environment. Unfortunately, limited to this level, we can't discuss these issues one by one. Note that the .NET framework usually distinguishes the environment when converting and formatting, unless you pass CultureInfo.invariantCulture to the formatting method. By default, the Visual Basic .NET built-in method usually does not distinguish the environment, please pay attention to this!

analysis

Use a string to convert a string into a variety of other types using the PARSE method to be converted to the Parse method. For example, to be converted to an integer, you can use the INT32.PARSE method. Note that the conversion can also be converted by other methods, such as the method in the Convert class; in some cases, the converted object type (in C #) can also be forced, or use the Visual Basic's CTYPE or CSTR function.

Fill and tailor

The spaces (or any other characters) can be filled in the left or right side of the string, both of which are Padlex and Padright methods. You can also route your designated spaces or any characters in the beginning and / or end of the string and / or ends through a variety of methods. These methods will be created and returned to a new string.

INSERT / REMOVE / Replace / Concat

These methods are similar to the methods in StringBuilder, but the overload in String is less than StringBuilder. For more information on these differences, see the "StringBuilder" section below.

INSERT is inserted into the specified string in the specified location to create a new string. Remove deletes the specified number of characters from the specified location, creating a new string. Replacing uses another character or string to replace all specified characters or strings to create and return a new string. The static method Concat is created and returned to a new string through the overloaded strings and / or objects transmitted.

Split / Join

Split and Join These two method functions are very powerful. Join is a static method that uses the specified string as a separator, partially or all strings in the delivered string array, creating and returning a string. Split uses a specified set of separator characters to split a string to a string array to create and return a string array.

Conversion

String does not directly access the conversion method, but the Convert class contains multiple static / shared conversion methods, most methods of TO ..., you can convert a string to a built-in type. Converting strings to built-in types, including Toboolean, Tobyte, Tochar, Todecimal, Todouble, Toint16, Toint32, Toint64, Tosbyte, Tosingle, Tostring, Touint16, Touint32, and Touint64. There is also a method to convert a string into a DateTime object, ie TodateTime; fromBase64String, and Tobase64String methods to implement conversion between byte array and Base64-encoded strings (useful to transfer binary data through text protocol).

String contains the TocharaRray method that converts strings into characters arrays. Also included in the conversion character case: TouPper and Tolower. INTERN / ISINTERNED

The .NET runtime preserved a string value pool in the application domain (substantially similar to the process). When it loads an assembly (for example, your program) into the application domain, the string of the set of string is merged with the string boundaries of the application domain, thereby avoiding repetition of string frequencies. . (Do not change the result of the program, because the string is unable to change.) In fact, all string frequencies are retained, so because each string often has only one copy, you can correctly String value is referenced comparisons.

However, if you generate a string (for example, one of the String methods that creates a new string, or using StringBuilder), the string will be different from the string of the same value as the string (assuming), Therefore, the reference comparison will fail. This problem may be very serious, because the reference is much more than the value, it only needs the address of the address. (So ​​if you really need a quick run code, you need to use a reference comparison under the premise of ensuring reference comparison!)

If you want to add your string to a regular pool, you can use a static method INtern, which adds a string into a regular pool (if you have not added to the pool) and return a reference to the constant value pool string. E.g:

[C #]

String S2 = New StringBuilder (). Append ("foo"). Append ("bar"). Tostring ();

String S3 = String.Intern (S2); // Return to a reference to the common value pool

String s = "foobar"; // Always in the constant value pool

Stringbuilder SB = New StringBuilder ();

Sb.append (Object.referenceequals (S2, S)); // False: Different

Sb.append (",");

Sb.append (Object.referenceequals (S3, S)); // true: the same

[Visual Basic .NET]

DIM S2 AS STRING = New _

Stringbuilder (). Append ("foo"). Append ("bar"). Tostring ()

DIM S3 AS STRING = String.Intern (S2) 'Returns reference to the common value pool

DIM S as string = "foobar" 'is always in a regular pool

DIM SB AS New StringBuilder ()

SB.Append (S2 IS S) 'FALSE: Different

sb.append (",")

Sb.append (s3 is s) 'true: the same

You can also use a static isInterned method to check if the string is already in the pool; if yes, returns True.

Gethashcode

You may remember, the last time we discussed this problem, that is, if Equals is overwritten, GetHashCode should also be covered. In String, Equals is overwritten, so GetHashCode is also overwritten, which provides good hash and performance. StringBuilder

You may have noticed that many methods in the string are created and returned to a new string. If you expect, distribute and discard a large number of string costs is very high.

Often, if you want to perform a string operation that needs to create a new string for a specific string, you can safely use the corresponding method in the string (or the appropriate Visual Basic .NET function). However, if you want to perform multiple this operation, and the required operations are provided in System.Text.StringBuilder, you should create a StringBuilder according to your string, then perform multiple operations on the StringBuilder, and finally in StringBuilder. Upset toString to return the result string. Refer to the previous example, in this example, all operations are completed in a row.

The usual approach is to generate a string in the StringBuilder, and it will be converted to a string. Note that call toString does not really replicate strings unless you have modified the same StringBuilder object later, it is very efficient, using StringBuilder's system overhead is just a replication operation, not two. This is why we use a regular rule. For two or more operations, the same effect can be obtained using StringBuilder.

You can also use StringBuilder if you can use more limited overloads in String.

To use StringBuilder, you will need to include Using System.Text at the beginning of the program file; (in Visual Basic is imports system.text).

StringBuilder has multiple constructors that initialize objects from strings and set their capacity and maximum capacity. (The default maximum capacity is about 2 billion characters, so although the larger value does not have problems, the smaller value is still relatively reasonable.) The capacity of the object can be raised as needed, as long as it does not exceed Maximum capacity. After constructing the StringBuilder, you cannot adjust its maximum capacity.

A total of four attributes: Capacity, MaxCapacity (read-only), Length, current length, can set shorter or longer) and Chars (Index Builder, used to read and write a single character) . If the capacity is not large enough, you can use the EnSureCapacity method to increase capacity.

Using an Append method, you can attach strings or any types (including many overloads) to the end of StringBuilder. If other types are passed, its toString method will be called, and the results are attached to the StringBuilder.

Using the AppendFormat method, you can format the string attached to the StringBuilder. Its formatted method is the same as String.Format and Console.WriteLine.

With many overloads of INSERT, you can insert strings in any location in StringBuilder (possibly by calling the toString method to call the parameters). Using REMOVE, you can delete any number of characters from any location.

With Replace, you can replace a single character, or replace the subtrial string as described above.

Finally, use the toString overload, you can create and return new String objects based on StringBuilder (or its specified substrings).

System.Text Encoder and Decoder

You must have noticed that all strings in the .NET framework are stored as 16-bit Unicode. But not everyone uses Unicode, so sometimes some other character codes are converted to Unicode, or Unicode converts Unicode to other character encodings.

The .NET framework provides a variety of classes that can be used to encode (convert the Unicode characters into another encoded byte block) and decoding (convert some encoded byte blocks into Unicode characters).

Each coding for support has a class: asciiencoding, codepageEncoding, UnicodeEncoding (for converting BIG-Endian to Little-Endian), UTF7Encoding and UTF8Encoding.

Each class contains methods for encoding (such as getBytes) and decodes (such as getChars), which can encode and decode an array at time. In addition, each class supports GetEncoder and getDecoder, which returns an encoder and decoder capable of maintaining a shift state, so it can be used for flow and block.

Regular expression

You may have noticed that Visual Basic .NET uses the LIKE statement to support only limited regular expressions. In addition, the .NET framework supports very complex regular expressions in the System.Text.RegularExpressions namespace. The key classes here are System.Text.RegularExpressions.Regex, which represents the compiled regular expression, and provides methods of using this expression, which can be used to find and replace a regular expression in a string, and put a string Remove the array of strings. The documentation about the regular expression is still very small, so we will not discuss it. In the future column, you may introduce.

转载请注明原文地址:https://www.9cbs.com/read-125542.html

New Post(0)