[英]How can I extract the first 4 digits from an int? (Java)
I'm looking to find a way to convert a string to an int in order to then extract and return the first 4 digits in this int. 我正在寻找一种方法将字符串转换为int,然后提取并返回此int中的前4位数字。
Note: It must remain as a String for the other methods to work properly, though. 注意:它必须保留为String,以便其他方法正常工作。
Try following: 试试以下:
String str = "1234567890";
int fullInt = Integer.parseInt(str);
String first4char = str.substring(0,4);
int intForFirst4Char = Integer.parseInt(first4char);
Wherever you want integer for first four character use intForFirst4Char
and where you wanna use string use appropriate. 无论你想要的前四个字符的整数使用intForFirst4Char
,你想在哪里使用适当的字符串使用。
Hope this helps. 希望这可以帮助。
Integer.parseInt(myIntegerString.substring(0, 4))
Also, read the JDK: 另外,阅读JDK:
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html http://download.oracle.com/javase/1.5.0/docs/api/java/lang /Integer.html
You can either use the following: 您可以使用以下内容:
Integer.parseInt("123".substring(0, 2))
OR 要么
int temp = 12345678;
int result = temp / (int)Math.pow(10, (int)(Math.log10(temp) - 1))
public class ExtractingDigits { 公共类ExtractingDigits {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int num = 1542,ans=0;
for(int i=1; i<=4; i++){
ans=num%10;
System.out.println(ans);
num = num/10;
}
}
} }
This will give you digits in an array 这将为您提供数组中的数字
public Integer[] convertNumbertoArrayLtoR(Integer[] array, Integer number, Integer maxDivisor, Integer i)
{
if (maxDivisor > 0)
{
Integer digit = number/maxDivisor;
array[i] = digit;
number = number%maxDivisor;
maxDivisor = (int) Math.floor(maxDivisor/10);
i++;
convertNumbertoArrayLtoR(array, number, maxDivisor, i);
}
return array;
}
Calling method 通话方式
digitArrayLR = convertNumbertoArrayLtoR(digitArrayLR, numberInput, maxDivisor, 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.