洛谷——P1308统计单词数

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);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值