一、字符串反转
题目:给定一个字符串,将该字符串反转输出。
public class StringReverse {
public static void main(String[] args) {
//设定一个字符串
String s = "abcdefg";
System.out.println("原来的字符串:" + s);
//方式一:使用java内置方法进行反转输出
StringBuilder stringBuilder = new StringBuilder(s);
String sr = stringBuilder.reverse().toString();
System.out.println("内置方法:反转后的字符串sr:" + sr);
System.out.print("遍历字符:反转后的字符串c:");
//方式二:遍历,从最后一个字符开始提取并输出
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
System.out.print(c);
}
System.out.println();
}
}
二、字符串转整型
题目:用算法将一个数字字符串转换成一个整数(不能使用java内置方法)
public class AToI {
//测试方法
public static void main(String[] args) throws Exception {
String s = "-312345";
System.out.println("转换后的数字为:" + AToI1(s));
System.out.println("转换后的数字为:" + AToI2(s));
}
/**
* 使用遍历的方式去实现
*/
public static int AToI1(String s) throws Exception {
if (s == null || s.length() == 0) {
throw new Exception("要转换的字符串为空,无法转换!");
}
int retInt = 0;
//设置一个整型数组
int[] num = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
//遍历每一个字符串,将单个字符转化为当个整型
switch (c) {
case '-':
//判断负整数
num[i] = -1;
break;
case '0':
num[i] = 0;
break;
case '1':
num[i] = 1;
break;
case '2':
num[i] = 2;
break;
case '3':
num[i] = 3;
break;
case '4':
num[i] = 4;
break;
case '5':
num[i] = 5;
break;
case '6':
num[i] = 6;
break;
case '7':
num[i] = 7;
break;
case '8':
num[i] = 8;
break;
case '9':
num[i] = 9;
break;
default:
throw new Exception("要转换的字符串格式错误,无法转换!");
}
}
for (int i = 0; i < num.length; i++) {
if (num[i] < 0 && i > 0) {
throw new Exception("要转换的字符串格式错误,无法转换!");
}
if (num[i] < 0) {
continue;
}
retInt += Math.pow(10, num.length - i - 1) * num[i]; //math函数实现各个数字的连接
}
//考虑到如果是一个负数的情况
if (num[0] == -1) {
retInt = -retInt;
}
return retInt;
}
/**
* 使用charAt去实现
*/
public static int AToI2(String s) throws Exception {
int retInt = 0;
if (s == null || s.length() == 0) {
throw new Exception("要转换的字符串为空,无法转换!");
}
boolean isNegative = false;
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
//判断第一位是不是负号
if (s.charAt(i) == '-') {
isNegative = true;
continue;
}
} else {
//判断是否为数字字符
if (s.charAt(i) > '9' || s.charAt(i) < '0') {
throw new Exception("要转换的字符串格式错误,无法转换!");
}
}
retInt *= 10;
retInt += s.charAt(i) - '0';
}
//三目运算实现正负数的返回
return isNegative ? -retInt : retInt;
}
}