String、正则
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29?tpId=37&tags=&title=&difficulty=&judgeStatus=&rp=1&gioEnter=menu&dayCountBigMember=%E8%BF%9E%E7%BB%AD%E5%8C%85%E6%9C%88
思路
大体是字符串操作,看到“;分割”想到split()方法,看到有输入格式的要求想到用正则表达式判断。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) {
int x = 0;
int y = 0;
String[] str = in.next().split(";");
for (String s : str) {
if (s.matches("[WASD][0-9]+") == true) {
switch (s.charAt(0)) {
case 'A' :
x = x - Integer.parseInt(s.substring(1));
break;
case 'D' :
x = x + Integer.parseInt(s.substring(1));
break;
case 'W' :
y = y + Integer.parseInt(s.substring(1));
break;
case 'S' :
y = y - Integer.parseInt(s.substring(1));
break;
}
}
}
System.out.println(x + "," + y);
}
}
总结
String的一些方法
1. .split(...),用来分割字符串
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] str = in.nextLine().split(";");
for (String s : str) {
System.out.println(s);
}
}
+-----------+
输入:
A;ABF;1a5
输出:
A
ABF
1a5
+-----------+
2. .substring(x)
public String substring(int beginIndex)
或
public String substring(int beginIndex, int endIndex)
public class RunoobTest {
public static void main(String args[]) {
String Str = new String("This is text");
System.out.print("返回值1 :" );
System.out.println(Str.substring(4) );
System.out.print("返回值2 :" );
System.out.println(Str.substring(4, 10) );
}
}
+-----------------+
返回值1 : is text
返回值2 : is te
+-----------------+
3. valueof和parseInt的区别
Integer.valueOf() 和 Integer.parseInt() 都是用于将字符串转换为整数的方法,但它们有一些区别:
返回类型:
Integer.valueOf() 返回的是 Integer 对象。
Integer.parseInt() 返回的是 int 类型的原始值。
异常处理:
Integer.valueOf() 如果无法解析字符串或字符串为 null,则返回 null。
Integer.parseInt() 如果无法解析字符串,会抛出 NumberFormatException 异常。
正则表达式
太多了,先按本题用的整理
[WASD][0-9]+
2个部分
部分1:[WASD] 只匹配这四个字母
部分2:[0-9]+ 匹配数字0-9至少出现一次。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] str = in.nextLine().split(";");
for (String s : str) {
if(s.matches("[WASD][0-9]+")){
System.out.println(s+":true");
}else{
System.out.println(s+":false");
}
}
}
+--------------------------------------+
输入:A1;D10;S12345;a6;Q886;WA;WW;WW5
输出:
A1:true
D10:true
S12345:true
a6:false
Q886:false
WA:false
WW:false
WW5:false
+--------------------------------------+
小细节!
case后面一定要加break啊,我服了,因为这个事儿我找了半小时bug!
李咸鱼刷题小结 文章被收录于专栏
总结一下我的刷题过程、错误以及学到的知识