题目:字符串转整型:例如给一个数字字符串。“123”转成数字123 "-123"转成数字-123 “--123”转成数字123
最后有完整代码
思路:
1、将字符串转化为 字符串数组用split();
split()方法说明: https://mp.csdn.net/postedit/89108906
2、计算出“-”的个数
3、去除掉“-” 并且使用System.arraycopy() 复制到数组
4、将新数组 转化成字符串,再转成整数类型
5、加上前面的符号判断。
源代码:
public class Test {
public static void change(String word){
int singel = 0;
String[] num = word.split("");
for(String m:num){
if(m.equals("-")){
singel++;
}else if(!m.equals("-")){
break;
}
}
String[] tmp = new String[num.length-singel];
System.arraycopy(num,singel,tmp,0,num.length-singel);
StringBuffer tmp1 = new StringBuffer();
for(int i = 0; i < tmp.length; i++){
tmp1.append(tmp[i]);
}
String s = tmp1.toString();
int end1 = Integer.parseInt(s);
int end = end1*(int)(Math.pow(-1,singel));
System.out.println(end);
}
public static void main(String[] args) {
change("----123");
}
}