问题描述
统计这篇短文用了多少个单词“to”。TherewasanAmericancouplewhohadnochildren,sotheywantedtoadoptachild.Finally,anorphanagecontactedthem,saying,"Wehaveababyforadoption.It'saRussianorphan."Thecouplewasdelightedandwenttobringthebabyhome.Onthewayhome,theystoppedbyauniversitytoenrollinaRussiancourse."WhydoyouwanttolearnRussian?TheEnglishthatwespeakisaverygoodlanguage,"theuniversitysecretaryasked."Well,wejustadoptedaRussianbaby.WhenhebeginstospeakRussianinafewyears,weareafraidthatwemightnotbeabletounderstandhim,"thecouplereplied.考虑的情况:句子首字母是to,一个单词里有to,比如too;
解决方案
解决方案二:
用正则匹配就OK了!
解决方案三:
同意楼上的
解决方案四:
同意楼上的
解决方案五:
importjava.io.*;publicclassCountChar{/***@paramargs*@throwsIOException*/publicstaticvoidmain(String[]args)throwsIOException{FileReaderfileIn=null;try{fileIn=newFileReader("D:\java\1.txt");}catch(FileNotFoundExceptione){System.out.println("找不到文件,程序将终止!");e.printStackTrace();System.exit(-1);}char[]cc=newchar[1024];try{fileIn.read(cc);}catch(IOExceptione){System.out.println("文件读入错误!");fileIn.close();}Stringstr1=newString(cc);String[]strArray=newString[1024];strArray=str1.split("to");intcount=strArray.length;System.out.println(""+count);}}
没考虑开头结尾,和to为一句话的结尾情况(如to,to?)太困了,睡了。
解决方案六:
Stringstr="TO,to,toto,aaaaa,too,ato";inttimes=str.length()-str.replaceAll("[To||to]","").length();System.out.print("to出现的次数"+times/2);
解决方案七:
还是用正则表达式吧。简单易懂。