In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to write Java String to int". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what is the way to write Java String to int"?
In Java, String (string) and int (shaping) are two different data types. Strings can put many strings together. Shaping is just shaping.
Students may wonder, can I not know this knowledge, please don't fool me? Just keep looking down. Can you skip some snacks or cold dishes before a big meal?
Sometimes, a string can simply contain some numbers, such as "123". You should have seen that when some operations require you to enter a mobile CAPTCHA, most of them are 6-digit or 4-digit random digits, and when they are passed to the server, the initial form is a string type. and then maybe turn it into plastic surgery to do some processing.
For Java, you can't add numbers of two string types directly through the "+" operator. Take a look at the following example.
String a = "100"; String b = "50"; String c = aquib; System.out.println (c)
The result of the program output is 10050, not 150. For strings, the "+" operator is used to concatenate, not to add.
The students may be in a hurry again. I also know this knowledge. Right away, the point will come right away.)
Then it is necessary to convert the string into shaping before doing the operation. There are two common practices:
The first, using Integer.valueOf (), returns a wrapper type Integer, which of course can be converted to int by automatically unpacking.
String a = "100"; String b = "50"; int A = Integer.valueOf (a); int B = Integer.valueOf (b); int c = Atom B; System.out.println (c)
The output of the program is as follows:
one hundred and fifty
The second, using Integer.parseInt (), returns a basic data type, int.
String a = "100"; String b = "50"; int A = Integer.parseInt (a); int B = Integer.parseInt (b); int c = Atom B; System.out.println (c)
The output of the program is as follows:
one hundred and fifty
Of these two methods, the second is preferred, because it does not involve automatic unpacking and has better performance.
The students may be impatient, is that all? All right, now the point really comes.)
In addition to the above two ways, can students think of the third one? Convert the string to shaping. Do you suddenly feel a little empty in your head?
Empty is right, when this article is the most knowledgeable, it comes! Here comes stumbling!
/ * * @ author Silent Wang er, an interesting programmer * / public class String2IntDemo {public static void main (String [] args) {String a = "100"; String b = "50"; int A = string2int (a); int B = string2int (b); int c = A + B; System.out.println (c) } public static int string2int (String s) {int num = 0; int pos = 1; for (int I = s.length ()-1; I > = 0; iMel -) {num + = (s.charAt (I) -'0') * pos; pos * = 10;} return num;}}
The output of this program is also 150. The discerning-eyed student may have found out what kind of magic method the string2int () method is and the effect of converting a string into plastic surgery.
First of all, we have to popularize a little bit of common sense. Students need to know something about ASCII codes, that is, all characters have codes to identify them-this code is ASCII codes.
Based on this, all numeric characters minus the character'0' will get the absolute value of that character, which is an integer.
String s = "520s"; System.out.println (s.charAt (2) -'0'); System.out.println (s.charAt (1) -'0'); System.out.println (s.charAt (0) -'0')
The output is as follows:
0 2 5
The string "520" has a length of 3, that is, the position of the subscript 2 is the single digit of the character '0percent color-number 520; the position of the subscript 1 is the ten digits of the character' 2percent color-number 520; and the position of the subscript 0 is the hundred digits of the character '5percent color-number 520.
Some smart students may have thought that, through a for loop, traversing the string, and then calculating the integer value at the current position, the single digit multiplied by 1, the ten digits multiplied by 10, the hundred digits multiplied by 100, and then added up, it is the integer value corresponding to the string.
Yes, that's what the string2int () method does. If the parameter is the string "520", the result is shaping 520; if the parameter is the string "100", the result is shaping 100; if the parameter is the string "50", the result is shaping 50.
If you are an aspiring programmer, you won't be too satisfied with both Integer.valueOf () and Integer.parseInt (), because it's just using other people's wheels. The custom method string2int () belongs to building wheels from beginning to end. At the thought of this, do you feel like you're starting to get better?
In fact, if you are willing to pull the source code, you will suddenly realize.
Let's first look at the Integer.valueOf () method:
Public static Integer valueOf (String s) throws NumberFormatException {return Integer.valueOf (parseInt (s, 10));}
What is called internally is the int parseInt (String s, int radix) method.
Let's take a look at the Integer.parseInt () method:
Public static int parseInt (String s) throws NumberFormatException {return parseInt (Scrim 10);}
What is called internally is also the int parseInt (String s, int radix) method, and the cardinality radix parameter is 10mi-did the students guess something?
Yes, your guess is close. Let's take a look at the source code of the int parseInt (String s, int radix) method:
Public static int parseInt (String s, int radix) throws NumberFormatException {/ * * WARNING: This method may be invoked early during VM initialization * before IntegerCache is initialized. Care must be taken to not use * the valueOf method. * / if (s = = null) {throw new NumberFormatException ("null");} if (radix
< Character.MIN_RADIX) { throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX"); } if (radix >Character.MAX_RADIX) {throw new NumberFormatException ("radix" + radix + "greater than Character.MAX_RADIX");} boolean negative = false; int i = 0, len = s.length (); int limit =-Integer.MAX_VALUE; if (len > 0) {char firstChar = s.charAt (0); if (firstChar
< '0') { // Possible leading "+" or "-" if (firstChar == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (firstChar != '+') { throw NumberFormatException.forInputString(s, radix); } if (len == 1) { // Cannot have lone "+" or "-" throw NumberFormatException.forInputString(s, radix); } i++; } int multmin = limit / radix; int result = 0; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE int digit = Character.digit(s.charAt(i++), radix); if (digit < 0 || result < multmin) { throw NumberFormatException.forInputString(s, radix); } result *= radix; if (result < limit + digit) { throw NumberFormatException.forInputString(s, radix); } result -= digit; } return negative ? result : -result; } else { throw NumberFormatException.forInputString(s, radix); } } 1)parseInt() 方法判断了 null 的情况,认为格式不正确。 2)然后判断了基数 radix 的情况,不能小于 2,不能大于 36。 3)if (len >0) determines the length of the string, and if it is empty, the format is also considered incorrect.
4) then judge the first character s.charAt (0). If it is a negative sign, the current string is considered to be a negative number; if it is not a positive sign "+", it is considered incorrect; if there is only one negative sign or positive sign, it is also considered incorrect.
In short, it is more rigorous than our custom method string2int ().
5) use the while loop to work with the more professional Character.digit (s.charAt (iTunes +), radix) to calculate the corresponding value of the character in each position, and then multiply it with the cardinality radix to calculate the final value.
It's a little different from string2int (), but the overall thinking is the same.
We can also refine the string2int () method to satisfy the case of negative numbers:
Public class S2IDemo {public static void main (String [] args) {String a = "- 100s"; String b = "50"; int A = string2int (a); int B = string2int (b); int c = A + B; System.out.println (c);} public static int string2int (String s) {boolean negative = false; char firstChar = s.charAt (0) If (firstChar = ='-') {negative = true; s = s.substring (1);} int num = 0; int pos = 1; for (int I = s.length ()-1; I > = 0; iMel -) {num + = (s.charAt (I) -'0') * pos; pos * = 10 } return negative?-num: num;}}
When the first character is a negative sign'-', the result returns a negative number and truncates the first bit of the original string. Other things remain the same, at this time, when an is "- 100" and b is "50", the result of a + b is-50.
At this point, I believe you have a deeper understanding of "what is the way to write Java String to int". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.