1https://www.luogu.com.cn/problem/P1308
统计单词数,找出里面有多少个单词以及单词的位置(单词首字母的位置)。
坑点:
1.主要是单词的大小写转化toLowerCase()、toUpperCase()
2.找出单词的下标,一开始去计算单词在文章中的个数,wa了两三次,这个就遍历一遍找出来就好了,遍历的时候要注意如果文章中第一个单词是对应单词和最后一个单词是对应单词的要单独拿出来,这是两种极端情况,然后剩下的,就判中间的情况就好了。
代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
String word=reader.next();//比对单词
word=word.toLowerCase();//将单词转为全部都是小写的
String a=reader.nextLine();
String test=reader.nextLine();//接收文章
String test_tmp=test;
test=test.trim();//去掉首尾空格
int index=-1;//单词坐标
boolean change=false;
int count=0;
String []spString=test.split("\\s+");//以空白划分文章
for(int i=0;i<spString.length;++i)
{
if(word.equals(spString[i].toLowerCase()))
{
++count;
}
}
//找出该单词首字母的位置
if(((test_tmp.substring(0,word.length()).toLowerCase()).equals(word) && (test_tmp.charAt(word.length())==' ')))
{
if(change==false)//只修改一次
{
index=0;
change=true;
}
}
else
{
for(int i=1;i<test_tmp.length()-word.length();++i)//遍历一遍,搜索该单词首字母的位置
{
if((test_tmp.substring(i,i+word.length()).toLowerCase()).equals(word)&&test_tmp.charAt(i-1)==' '&&test_tmp.charAt(i+word.length())==' ')
{
if(change==false)//只修改一次
{
index=i;
change=true;
}
}
}
if(((test_tmp.substring(test_tmp.length()-word.length(),test_tmp.length()).toLowerCase()).equals(word) && (test_tmp.charAt(test_tmp.length()-word.length()-1)==' ')))
{
if(change==false)//只修改一次
{
index=test_tmp.length()-word.length();
change=true;
}
}
}
if(count==0)
System.out.println(index);
else
System.out.println(count+" "+index);
}
}