洛谷官方题单[Java版题解]--【入门5】字符串
知识点:sc.next()不吃换行符,留在缓冲区,sc.nextLine()吃掉换行符,但只返回换行符前面的,然后该它上场的时候前面有换行符留在缓冲区,他就会卡住,
import java.util.Scanner; public class Main { static int pos=0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); /* String s = sc.next(); String s1 = sc.nextLine();*/ //next() 读一个字符(遇到空格或换行就停) 不留,但换行符还在缓冲区 //nextLine()读一整行(从当前位置读到换行符) 吃掉换行符,然后nextLine遇到新的换行符就停止,比如该他上场了,但前面还有一个换行符留在缓冲区,它就卡了 String s1=sc.nextLine(); String S3=sc.nextLine(); String[] s2 = S3.split(" "); int count = 0; for (int i = 0; i < s2.length; i++) { if (s1.equalsIgnoreCase(s2[i])) { count++; } } int c = look(s2, s1); if (count == 0) { System.out.println(-1); } else { System.out.println(count + " " + c); } } public static int look(String [] s, String s1) { //读取的是单词首字母的位置 for (int i = 0; i < s.length; i++) { if(s1.equalsIgnoreCase(s[i])){ return pos; } pos+=(s[i].length()+1); } return -1; } }