.NET Core C # Part 2-5 Intermediate common utility classes

.NETCore CSharp Intermediate articles 2-5

This section is a practical use of common classes and methods

String.Format

string.format is a formatted string class, some of which it converts a character string is written in a specified format.

Several definitions String.Format method:

  • String.Format (String, Object) format of the item specified String replacement text equivalent to Object instance specified value.
  • String.Format (String, Object []) specified text equivalent value corresponding Object instance specified array format item is replaced in a String.
  • String.Format (IFormatProvider, String, Object []) Replaces the format specified in the corresponding text String value equivalent Object instances of the specified array. Specified parameter supplies culture-specific formatting information.
  • String.Format (String, Object, Object) Replaces the format specified in the text String equivalent values ​​of the two specified Object instance.
  • String.Format (String, Object, Object, Object) Replaces the format specified in the text String equivalent three values ​​specified Object instance.

It looks very abstract, in fact string.format wording is somewhat similar to our regular expressions. We focus on to talk about a few very common usage.

Value format

character Explanation Examples Export
C Currency format, followed by a number for the number of decimal places string.Format("{0:C3}", 2) Obtain current currency format settings, for example, or ¥ 2.000 $ 2.000
D Decimal, followed by a number of filler bits 0 to N forward string.Format("{0:D3}", 2) 002
X Corresponding to the output of the hexadecimal string.Format("{0:X000}", 12) C
G General output string.Format("{0:G}", 2) 2
N Numbers separated by a semicolon string.Format("{0:N}", 250000) 250,000.00
customize Custom output string.Format("{0:000.000}", 12.2) 012.200

Notably, the braces is a placeholder, {0:} represents the first parameter is followed, {1:} is the second, is present as a placeholder.

Placeholder

Placeholders are two types:

  • 0 placeholder zero: if the value of the format of "0" appears in the position of a digital in format, this number is copied to the result string. After the decimal point before the leftmost "0" and the decimal point position "0" in the rightmost position to determine the total range of numbers appears in the result string.
    "00" so that the specifier value before the decimal point are rounded to the nearest number, where zero is always discarded.

  • Digital placeholder #: If the value of the format "#" position in format appears in a number, this number is copied to the result string. Otherwise, the result string This position does not store any value.
    Note that if "0" is not a valid number, this specifier never displays "0" character, even if "0" is a unique string of numbers. If "0" is a valid digit number displayed in the "0" character is displayed. "##" format string such that the value is rounded to the nearest decimal numbers before, where zero is always discarded.

PS: blank placeholders

string.Format("{0,-50}", theObj);//格式化成50个字符,原字符左对齐,不足则补空格
string.Format("{0,50}", theObj);//格式化成50个字符,原字符右对齐,不足则补空格

For example, for fixed regional custom format string "dddd, dd MMMM yyyy".

Time Format

Formatting time is very simple, we generally describe the time all year - month - day hours: minutes: seconds is enough, in String.Format class, we take these words describe the first letter of the English as a formatting characters, such as 1999- 05-06 I need to convert foreign common expressions 05/06/99 time, we just need to

"1999-05-06".Format("mm/dd/yy");

Very simple. We include a detailed table of commonly stated time formatting characters
| Character | Description | Details
|: -: |: -: |: -: |
| d | Short date pattern | ShortDatePattern represented by the current property defined custom DateTime format string. For example, for fixed regional custom format string "MM / dd / yyyy".
| D | Long date mode | custom DateTime format string represented by the current LongDatePattern attribute definition. For example, "dddd, dd MMMM yyyy" .
| F | complete date / time mode (short-time) | represents long date (D) and a combination of short-time (t) mode, separated by a space.
| F | full date / time pattern (long) | represents the custom DateTime format string defined by the current FullDateTimePattern property. For example, for fixed regional custom format string "dddd, dd MMMM yyyy HH: mm: ss".
| G | general date / time mode (short-time) | short date indicate that a combination (d) and short (t) mode, separated by a space.
| G | general date / time pattern (long) | represents short date (D) and a combination of time (T) mode, separated by a space.
| M or m | day of Mode | custom DateTime format string represented by the current MonthDayPattern attribute definition. For example, for fixed regional custom format string "MMMM dd".
| T | short mode | represents the custom DateTime format string defined by the current ShortTimePattern property. For example, for fixed regional custom format string "HH: mm".
| T | LP mode | custom DateTime format string represented by the current LongTimePattern attribute definition. For example, for fixed regional custom format string "HH: mm: ss".
| Y or y | date mode | represents the custom DateTime format string defined by the current YearMonthPattern property. For example, for fixed regional custom format string "yyyy MMMM".

There are some custom method, such as the examples I cited before the
| character | Description | Details
|: -: |: -: |: -: |
| N a d | day of the month will be represented as a number from 1-31 . | N is d at a time in front of a valid bit plus smaller than N 0
| N a M | digital representation from the month 1 to 12. | N number d is the time valid bit plus 0 in the front is smaller than N
| N number y | expressed in | N number y is at time significant bits preceded by a 0 is less than N, in particular, a y is the use of after two years were represented.
| N th S | represented as a number from 0 seconds to 59. | S represents an integer number of seconds elapsed from the previous minute of | N s th significant bit is added at time 0 in the front is smaller than N
| N m th | represents the number of minutes of from 0 to 59. | Represents the number of minutes since the full minute after the last hour of | N m-bit is active at a time preceded by less than N 0
| N th h | when expressed as a number from 0 to 12. | Since midnight or noon hour counting the whole | N h a valid bit is added at time 0 in the front is smaller than N
| N a H | it is expressed as a number from 0 to 24. | Since midnight or noon on the hour counting | h when the N bit is in the active time is less than N 0 preceded
enumerated String Format

Format string

character Explanation
G or g If possible, the enumerated items are displayed as a string value, an integer value or displays the current instance. If the enumeration definition Flags attribute is set, and the string value for each valid entry each value of the series are separated by commas. If the Flags property is not set, then the invalid value is displayed as digital items.
F or f If possible, the enumerated items are displayed as a string value. If the sum of the values ​​can be displayed as full enumeration (even if not provided Flags attribute), and the string value for each respective value of the series of valid entries separated by commas. If the value can not be determined entirely by the enumeration, the value is formatted as an integer value.
D or D As short as possible will be represented in the form enumeration displayed as an integer value.
X or x The enumeration is displayed as a hexadecimal value. The values ​​are expressed as needed with a leading zero length value in order to ensure a minimum of eight

DateTime

DateTime is C # processing time big kill, its efficiency is very high, significantly better than the time for other languages, wherein DateTime type rewrite ToString () method, in which ToString method DateTime, we can easily use our formatting characters to format it.

In fact DateTime structure we are talking about today is not the subject, because DateTime operation in fact is our string.Format operation up to us to talk about the conversion and string DateTime

Conversion into a string in the format of time DateTime structure only need to use

DateTime.Parse(str);

We explain this section is primarily calculated using the time TimeSpan class, but also in the DateTime function for some time to calculate, for example,

  • Add TimeSpan specified value to the value in this instance.
  • AddDays the specified number of days to the value in this instance.
  • AddHours the specified number of hours to the value in this instance.
  • AddMilliseconds the specified number of milliseconds is added to the value of this example.
  • AddMinutes the specified number of minutes on the added value of this example.
  • AddMonths the specified number of months the value was added to this example.
  • AddSeconds the specified number of seconds to the value in this instance.
  • AddYears the specified number of the year to the value in this instance.
  • Subtract from this instance subtracts a specified time or duration.

    TimeSpan

    The following list illustrates the portion of the TimeSpan methods

  • Add: are added to another TimeSpan value.
  • Days: Returns the number of days the TimeSpan value calculation.
  • Hours: Returns the value h calculated TimeSpan
  • Milliseconds: return TimeSpan value in milliseconds.
  • Minutes: return TimeSpan value min calculated.
  • Negate: Returns the opposite of the current instance.
  • Seconds: return TimeSpan value in seconds.
  • Subtract: subtract one from the TimeSpan value.
  • Ticks: Returns the number of tick TimeSpan value.
  • TotalDays: return TimeSpan value indicates the number of days.
  • TotalHours: Returns the number of hours indicated TimeSpan value.
  • TotalMilliseconds: Returns the number of milliseconds TimeSpan value representation.
  • TotalMinutes: Returns the number of minutes indicated TimeSpan value.
  • TotalSeconds: return TimeSpan value indicates the number of seconds.

StringBuilder

String objects are immutable, each time one of the methods in use System.String class, you create a new string object in memory, which requires the allocation of new space for the new object. If you frequently need to manipulate strings object, then use the string directly add and subtract is not cost effective approach at this time, we need to use our StringBuilder class operation.

StringBuilder free to expand the size, because StringBuilder allocated heap.

StringBuilder can specify the size and, when the specified allocation size, performance can be enhanced. Before reaching capacity, it will not re-allocate space for itself. If more than the specified size will be doubling the current size, it 10,15,20. Recommendations specified size.

Several commonly used method

  • StringBuilder.Append // information appended to the end of the current StringBuilder.
  • StringBuilder.AppendFormat // replaced with formatted text string passed format specifier.
  • StringBuilder.Insert // string or object at the specified index into the current StringBuilder object.
  • StringBuilder.Remove // ​​remove a specified number of characters from the current StringBuilder object.
  • StringBuilder.Replace // replace the specified character at the specified index.

One thing is worth noting that, for C #, Microsoft's String has a special type of optimization, if the two strings are the same content, then they will only be created once, that would point to the same memory address, and, C # compare there are three methods

  • It is more == stack which are equal values ​​(comparison value)
  • It is stack Equals comparison value which is equal (compare reference address value)
  • Object.ReferenceEquals (obj1, obj2) it is more of a memory address are equal

Example:

StringBuilder MyStringBuilder = new StringBuilder("Hello   World!",30);  
MyStringBuilder.Insert(6,"test");
MyStringBuilder.Append("test");

You only need to remember that in the face of a large number of string handling operation, we use StringBuilder to improve our processing speed.

If my post helped you, you github.NETCoreGuide project helped me a star, a concern and recommendation in the garden midpoint blog.

Github

BiliBili Home

WarrenRyan'sBlog

Blog Park

Guess you like

Origin www.cnblogs.com/WarrenRyan/p/11407921.html