有时候在做一些基础的数据结构的题中,经常可能会有接收一些字符串,字符串中含有数字,然后要求对其中的数字进行运算。这就需要提取其中的数字,再进行运算。
我以前经常是这样进行转换的:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
int a = str.length();
int [] array = new int[a];
for(int i=0; i<a; i++){
**array[i] = Integer.parseInt(String.valueOf(str.charAt(i)));**
}
}
}
今天在看别人写的答案的时候,发现有人是这样进行转换的:
将上面的加黑的代码替换成下面这行代码
**array[i] = str.charAt(i)-'0';**
原理其实很简单,就是利用ASCII值,进行转换的。自己原来没想过用这种方法来进行转换。

1295





