如何将字符串转换为整数?

我有一个文本框,让用户输入一个数字:

EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();

这个值被赋值给字符串hello。

我想把它转换成一个整数,这样我就能得到他们输入的数字;稍后将在代码中使用它。

是否有方法将EditText转换为整数?这样就跳过了中间人。如果不是,字符串到整数就可以了。


当前回答

你应该将String转换为float。它正在起作用。

float result = 0;
 if (TextUtils.isEmpty(et.getText().toString()) {
  return;
}

result = Float.parseFloat(et.getText().toString());

tv.setText(result); 

其他回答

有五种转换方法 第一种方法:

String str = " 123" ;
int i = Integer.parse(str); 
output : 123

第二种方式:

String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123

第三种方式:

String str"123";
int i = new Integer(str);
output "123 

第四种方式:

String str"123";
int i = Integer.valueOf(Str);
output "123 

第五种方式:

String str"123";
int i = Integer.decode(str);
output "123 

可能还有其他办法 但我现在只记得这些

使用正则表达式:

int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));

输出:

i=123;
j=123;
k=123;

科特林

可以使用Extension方法将它们解析为其他基本类型。

“10”toInt(。) “10”请(。) “真正的”toBoolean()。 “10 . 0”toFloat()。 “10 . 0”toDouble()。 “10”toByte(。) “10”toShort(。)

Java

String num = "10";
Integer.parseInt(num );

将字符串转换为int的最佳方法是:

 EditText et = (EditText) findViewById(R.id.entry1);
 String hello = et.getText().toString();
 int converted=Integer.parseInt(hello);

使用正则表达式:

String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""));

输出: 我= 1234;

如果你需要第一个数字组合,那么你应该尝试下面的代码:

String s="abc123xyz456";
int i=NumberFormat.getInstance().parse(s).intValue();

输出: 我= 123;