题目:
字符中所有出现的数字前后加上符号“*”,其他字符保持不变
解析:
题目比较简单,不动脑子直接判断也可以做出来:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String str = scanner.nextLine();
System.out.println(changeStr(str));
}
}
public static String changeStr(String str) {
String strNew = new String();
if (str.length() == 1 && judgeChar(str.charAt(0))) {
strNew = "*" + str.charAt(0) + "*";
return strNew;
} else if (str.length() >= 1 && judgeChar(str.charAt(0)) && !judgeChar(str.charAt(1))) {
strNew = "*" + str.charAt(0) + "*";
} else if (str.length() >= 1 && judgeChar(str.charAt(0)) && judgeChar(str.charAt(1))){
strNew = "*" + str.charAt(0);
} else if (str.length() == 1){
strNew = str.charAt(0) +"";
return strNew;
} else {
strNew = "" + str.charAt(0);
}
for (int i = 1 ; i < str.length()-1;i++) {
if (judgeChar(str.charAt(i)) && !judgeChar(str.charAt(i+1)) && !judgeChar(str.charAt(i-1))) {
// 如果是单个数字,那就夹住
strNew = strNew + "*" + str.charAt(i) + "*";
} else if (judgeChar(str.charAt(i)) && !judgeChar(str.charAt(i-1))) {
strNew = strNew + "*" + str.charAt(i);
} else if (judgeChar(str.charAt(i)) && !judgeChar(str.charAt(i+1))) {
strNew = strNew + str.charAt(i) + "*";
} else {
strNew = strNew + "" + str.charAt(i);
}
}
if (judgeChar(str.charAt(str.length()-1)) && !judgeChar(str.charAt(str.length()-2))) {
strNew = strNew + "*" + str.charAt(str.length()-1) + "*";
} else if (judgeChar(str.charAt(str.length()-1))) {
strNew = strNew + str.charAt(str.length()-1) + "*";
} else {
strNew = strNew + str.charAt(str.length()-1);
}
return strNew;
}
public static boolean judgeChar (char ch) {
return ch >= '0' && ch <= '9';
}
}
这样写校验的过程还是比较复杂的,稍微优化下,动动小脑筋就可以五分钟AC这道题,代码如下:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String str = scanner.nextLine();
System.out.println(changeStr(str));
}
}
public static String changeStr(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0;i < str.length();i++) {
if (judgeChar(str.charAt(i))) {
sb = sb.append("*").append(str.charAt(i)).append("*");
} else {
sb = sb.append(str.charAt(i));
}
}
return sb.toString().replace("**","");
}
public static boolean judgeChar (char ch) {
return ch >= '0' && ch <= '9';
}
}