How to resolve string to int ?)

Source: Internet
Author: User
Tags parse string
Q: How to resolve a string to an int?

A: There are three simple methods:

String source = "1412 ";
Int result = 0;

// Use convert. toint32 (string value );
Result = convert. toint32 (source );

// Use int32.parse (string value );
Result = int32.parse (source );

// Use int32.tryparse (string S, out int result );
Int32.tryparse (source, out result );

Q: What are the differences between the three methods?

A: A simple answer is:

If the parsing fails, int32.parse (source) will always throw an exception; convert. toint32 (source) does not throw an exception when source is null, but simply returns 0 to the caller. int32.tryparse (source, result) does not throw an exception in any case, only true or false is returned to indicate whether the resolution is successful. If the resolution fails, the caller will get a value of 0.

Q: If the literal value of the string to be parsed is not in decimal format, the returned values obtained from these methods are incorrect. Is there any solution?

A: You need to reload the corresponding versions of these methods. A simple method is to use the convert class.

Public static int toint32 (string value, int frombase );

The frombase value can only be 2, 8, 10, or 16, which is used to specify the hexadecimal mode. If frombase is not a specified value or the value is not in decimal format and has a positive or negative prefix, argumentexception is thrown.

String source = "0x1412"; // The 0x (or 0x) prefix here is optional.
Int result = convert. toint32 (source, 16 );

Of course, you can also

Public static int parse (string S, numberstyles style );

Specify numberstyles. allowhexspecifier or numberstyles. hexnumber as the second parameter to parse the string of the hexadecimal literal value. In this case, you need to reference the system. Globalization namespace.

Or use the int32 class

Public static bool tryparse (string S, numberstyles style, iformatprovider provider, out int result );

Specify numberstyles. allowhexspecifier or numberstyles. hexnumber as the second parameter, and null as the third parameter to parse the string of the hexadecimal literal value. Of course you should also reference the system. Globalization namespace.

Note that no matter whether the parse or tryparse method is used to parse the hexadecimal format, the character string cannot contain the 0x or 0x prefix. Otherwise, an exception is thrown.

Q: What if I want to convert string represented by scientific notation to int?

A: You can set numberstyles. allowdecimalpoint | numberstyles. allowexponent (bitwise operation of two nunberstyles enumeration values, the former indicates that there may be a decimal point, and the latter indicates that there may be an exponential symbol of scientific Notation) as the second parameter passed to int32 class

Public static int parse (string S, numberstyles style );

Or

Public static bool tryparse (string S, numberstyles style, iformatprovider provider, out int result );

If the parsed result is incompatible with the int, you need to store the result in another type. For example, "1.412e2" should store the parsing result in a float, double, or decimal type variable. Of course, you should also use the type method corresponding to the storage variable for parsing:

Double result = double. parse ("1.412e2", numberstyles. allowdecimalpoint | numberstyles. allowexponent );

The entire string expression should have no space. Otherwise, an exception may be thrown.

The scientific Note format is [{+ |-}] M. dddddd {e | e} [{+ |-}] XX, which can be divided into the following forms:

  • [-] M. dddddde + xx
  • [-] M. dddddde-xx
  • [-] M. dddddde + xx
  • [-] M. dddddde-xx

Which of the following statements cannot be parsed properly:

  • "1.412 E3"
  • "1.412e 3"
  • "1.412e + 3"
  • "142.16e-2"

Q: How do I deal with spaces contained in the string to be parsed?

A: you also have a variety of options for the string prefix or suffix space. Generally, you can directly use the string class

Public String trim ();

To take the spaces that may be contained at the end of the U-turn:

Int result = int32.parse (textbox1.text. Trim ());

Alternatively, you can use numberstyles. allowleadingwhite | numberstyles. allowtrailingwhite to tell parse or tryparse that the header and tail of the string to be parsed may contain spaces.

Int result = int32.parse (textbox1.text, numberstyles. allowleadingwhite | numberstyles. allowtrailingwhite );

If the string to be parsed is represented by scientific notation, you can

Int result = int32.parse ("1.412e3", numberstyles. Float );

Numberstyles. Float tells the parse method that the string to be parsed may contain spaces with the prefix or suffix, plus or minus signs with the prefix, (decimal point), and scientific notation index representation.

Q: How do I parse currency strings?

A: You can specify numberstyles. Currency to tell parse or tryparse that the string to be parsed is a currency style. Numberstyles. Currency indicates that the string to be parsed may contain prefix or suffix space, prefix plus or minus signs, decimal points, kilobytes, and literal values may be integers or decimal places:

Int result = int32.parse ("$1,412", numberstyles. Currency );

However, the currency style string cannot contain any hexadecimal symbols. In addition, the settings of the currency style string format are based on the settings in region and ages options (Region and language options.

Q: What if I change the settings in the system's region and languages options (Region and language options) but want to parse the strings according to the settings?

A: At this time, the numberformatinfo class will appear. This class allows you to directly tell the relevant methods how to process the symbols in the string without making any modifications to the system settings.

Correspondingly, we use the related attributes of numberformatinfo to set the settings in the currency (currency) tab of customerize regional options (custom region options:

Numberformatinfo Currency (currency)
Currencysymbol Currency symbol (currency)
Currencypositivepattern Positive currency format (currency positive number format)
Currencynegativepattern Negative currency format (currency symbol format)
Currencydecimalseparator Decimal symbol (decimal point)
Currencydecimaldigits No. of digits after decimal (decimal)
Currencygroupseparator Digit grouping symbol (digital grouping symbol)

Here, the digit grouping (digital grouping) in the currency (currency) tab of customerize regional options (custom region options) must be set with the currencygroupseparator and currencygroupsizes attributes of numberformatinfo. The setting values of the currencypositivepattern and currencynegativepattern attributes of numberformatinfo are limited:

Currencypositivepattern
Value Associated Pattern
0 $ N
1 N $
2 $ N
3 N $

Currencynegativepattern
Value Associated Pattern
0 ($ N)
1 -$ N
2 $-N
3 $ N-
4 (N $)
5 -N $
6 N-$
7 N $-
8 -N $
9 -$ N
10 N $-
11 $ N-
12 $-N
13 N-$
14 ($ N)
15 (N $)

Q: How should I use a set numberformatinfo instance?

A: numberformatinfo is an implementation of the iformatprovider interface. You can pass the numberformatinfo instance as a parameter to the corresponding overload method.

Q: Can the settings in the numbers (number) tab in customerize regional options (custom region options) be set through the corresponding numberformatinfo attributes?

A: Not all. Display leading zeros (zero start display), list separator (list separator), and measurement system (Scale System) do not exist. Negative Number Format (negative number format) the negativesign, numberdecimaldigits, and numberdecimalseparator of numberformatinfo must be used together. Other attributes can be found in numberformatinfo.

Q: Where are the settings of the display leading zeros (zero start display), list separator (list separator), and measurement system?

A: Sorry, so far I cannot find the corresponding place to set it. If you or others find it, please be sure to tell me. (However, you can use the read-only attribute regioninfo. ismetric to check whether the current system uses the metric (metric) system .)

Q: If I cannot infer which one or more numberstyles enumeration should be used for the string to be parsed?

A: This will not happen in general. The strings to be parsed must have a certain purpose or purpose. These purposes or purposes are constraints of the string literal style, the role of numberstyles enumeration is to illustrate this constraint. Of course, if you cannot deduce it, you can use numberstyles. Any enumeration.

Q: In the specific encoding process, how do I know which method should I choose to parse the string?

A: Personally, I will:

  • First, you need to know whether the CLR version you are using provides some method support. For example, tryparse is supported by. NET 2.0 or later.
  • Second, you can choose to use the method to overload the signature. If you want to parse a non-decimal string, convert. toint32 may be your only choice. Except in decimal and hexadecimal notation, you can use it to parse binary and octal values. However, you cannot use int32.parse or int32.tryparse to explain these hexadecimal strings. Of course, either in decimal or hexadecimal format can be used.
  • In addition, if you need to use numberstyles enumeration to inform the relevant method of the string style to be parsed, convert. toint32 will not help you. In this case, you should select int32.parse or int32.tryparse for the corresponding overload.
  • Again, if you do not want to handle exceptions in your code, int32.tryparse may be your only choice. You may determine whether the resolution is successful based on the result returned by it, then decide whether to use the resolution result. However, if you want to notify the caller of resolution failure through the exception mechanism, int32.parse or convert. toint32 is a good choice.
  • Finally, the selection criteria cannot be unique or general. You may sum up the selection criteria that suit you in practice. If you have a better choice method, please let me know.

Q: In. net, is there a similar method to parse a string to another primitive type?

A: Yes. In. net, we provide convert. To for these primitive types.Primitivetype,Primitivetype. Parse,PrimitivetypeThe. tryparse (. NET 2.0 or later) method is used to parse string into the corresponding primitive type. Of course, you must first ensure that the string literal value to be parsed is compatible with the corresponding primitive type. These primitive types are (the corresponding C # keyword in parentheses): sbyte (sbyte), byte (byte), int16 (short), uint16 (ushort), int32 (INT ), uint32 (uint), int64 (long), uint64 (ulong), char (char), single (float), double (double), Boolean (bool), decimal (decimal ). In addition ,. net also provides a method to parse the string into the datetime structure, in addition to the three methods mentioned above (convert. todatetime, datetime. parse, datetime. in addition to tryparse), we can also use datetime. tryparseexact. All of these methods are similar. The difference lies in the provisions on the string literal format (including its symbols). If you are interested, you can refer to the following msdn documents or other special topics.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.