帮你单步调试了一下
这句话:
if(Character.isWhitespace(text.charAt(index-1))&&(Character.isWhitespace(text.charAt(index+1+andStr.length())))
改成:
if(Character.isWhitespace(text.charAt(index-1))&&(Character.isWhitespace(text.charAt(index+andStr.length())))
就是你多加了一个1祝你好运!!!
这句话:
if(Character.isWhitespace(text.charAt(index-1))&&(Character.isWhitespace(text.charAt(index+1+andStr.length())))
改成:
if(Character.isWhitespace(text.charAt(index-1))&&(Character.isWhitespace(text.charAt(index+andStr.length())))
就是你多加了一个1祝你好运!!!
/**
* @author Administrator
*
* 更改所生成类型注释的模板为
* 窗口 > 首选项 > Java > 代码生成 > 代码和注释
*/
public class Search {
public static void main(String[] args) {
String text =
"To be or not to be ,thaht is question:"
+ "Whether 'tis nobler in the mind to suffer"
+ "the slings and arrows of outrageous fortune,"
+ "or to take arms against a sea of trubles,"
+ " and by opposing end them?";
int andCount = 0;
int theCount = 0; int index = -1; String andStr = "and";
String theStr = "the"; index = text.indexOf(andStr);
goOn : while (index >= 0) { if (Character.isWhitespace(text.charAt(index - 1))
&& (Character.isWhitespace(text.charAt(index + andStr.length())))
//开始检查字符串两边是否是空格,以确定是否是单个的字符串。
&& index != text.length()) {
++andCount;
index += andStr.length();
index = text.indexOf(andStr, index);
} else {
index += andStr.length();
index = text.indexOf(andStr, index);
continue goOn; //如果不成立就继续别的字符 }
}
index = text.indexOf(theStr);
System.out.println(index);
onGo : while (index >= 0) {
if (Character.isWhitespace(text.charAt(index - 1))
&& (Character.isWhitespace(text.charAt(index + andStr.length())))
&& index != text.length()) {
theCount++;
index += theStr.length();
index = text.indexOf(theStr, index);
} else {
index += theStr.length();
index = text.indexOf(theStr, index);
continue onGo; //如果不成立就继续别的字符
} }
System.out.println(
"The text contains"
+ andCount
+ "ands\n"
+ "the text contains"
+ theCount
+ "thes");
}
}
String text="To be or not to be ,thaht is question:"
+"Whether 'tis nobler in the mind to suffer"
+"the slings and arrows of outrageous fortune,"
+"or to take arms against a sea of trubles,"
+" and by opposing end them?";
System.out.println("text"+text);//
int i=0;
int j=0;
String strValue=null;
StringTokenizer st = new StringTokenizer(text," ");
while (st.hasMoreTokens()) {
strValue=st.nextToken();
if (strValue.equals("and")) {
i++;
}
if(strValue.equals("the")){
j++;
}
}
System.out.println("The text contains "+i
+" ands\n"+"the text contains "+j+" the");
ps:
The text contains 2 ands
the text contains 1 the是因为 suffer"+ "the 是一个单词 sufferthe ,要不看看上面的text打印出来就知道