0

我有字符串,我想将其转换为整数。

示例 - 我有以下格式的字符串

输入 : ABCD00000123

输出:123

提前致谢

4

3 回答 3

8
// First remove all non number characters from String 
input= input.replaceAll( "[^\\d]", "" );  
// Convert it to int
int num = Integer.parseInt(input);

例如

input = "ABCD00000123"; 

input= input.replaceAll( "[^\\d]", "" );   

输入将是“00000123”

 int num = Integer.parseInt(input);

int将是 123。

如果输入始终采用问题中提到的格式,这是一种简单的解决方案。考虑数字字符相对于非数字字符的位置可能有多种情况,例如
0123ABC
0123ABC456
ABC0123DE

于 2013-06-10T06:42:10.170 回答
1
String s = "ABCD00000123"
int output = Integer.parseInt(s.subString(4));

System.out.println(output);
于 2013-06-10T06:43:13.020 回答
0

我可以告诉你它的逻辑......将此字符串转换为字符数组,然后从第一个索引(数组为0)解析它,直到长度并检查第一个非零整数,然后从那个位置到 String 的剩余长度,将其复制到另一个 String,然后使用 Integer.parseInt() 解析它;

String val = "ABCD00000123";
String arr[] = val.toCharArray();
int cnt;
for(cnt = 0 ; cnt < arr.length; cnt++){
switch(arr[cnt]){

/*Place your logic here to check the first non-zero number*/

}
}

然后按照剩下的逻辑。

如果你有足够的编程概念,那么只有你能做到……

于 2013-06-10T06:45:47.477 回答