日期:2014-05-20 浏览次数:20929 次
import java.util.Scanner; public class Counter { public int counter(String inputs, String word) { int counter = 0; int index =0; for (int i = 0; i <= inputs.length() - 1; i++) { if ( ( index = inputs.indexOf(word) ) !=-1 ) { counter++; inputs = inputs.substring(index+word.length()); } } return counter; } public static void main(String[] args) { Scanner input = new Scanner(System.in); Counter find = new Counter(); System.out.print("请输入一个字符串:"); String inputs = input.next(); System.out.print("请输入要查找的字符:"); String word = input.next(); int num = find.counter(inputs, word); System.out.println(inputs + "中包含" + num + "个" + word); } }
------解决方案--------------------
import java.util.Scanner; public class Counter { public int counter(String inputs, String word) { int counter = 0; int index =0; // // for (int i = 0; i < inputs.length() - 1; i++) { //要用 <= // if (inputs.indexOf(word) == 0) { //要换成!=-1 !=-1意为找到一次,让count++才有意义 // counter++; // index++; //仔细看看你的index,哪都没用到,这是毛用... // } // } // return counter; for (int i = 0; i <= inputs.length() - 1; i++) { if ( ( index = inputs.indexOf(word) ) !=-1 ) { //上句代码意思为若inputs="abcdefgabckabcii" // word="abc"; //则每找到一次abc就,让inputs=从c后的那个d开始形成的子串即为defgabckabcii; //然后再循环往覆,直到结束. //而上面的for(循环其实意思不大),最好直接用 // while(( index = inputs.indexOf(word) ) !=-1 ){ // counter++; // inputs = inputs.substring(index+word.length()); // } } } return counter; } public static void main(String[] args) { Scanner input = new Scanner(System.in); Counter find = new Counter(); System.out.print("请输入一个字符串:"); String inputs = input.next(); System.out.print("请输入要查找的字符:"); String word = input.next(); int num = find.counter(inputs, word); System.out.println(inputs + "中包含" + num + "个" + word); } }
------解决方案--------------------
String str = "aafcfasfqefdsasfaff"; //e表示需要匹配的数据,使用Pattern建立匹配模式 Pattern p = Pattern.compile("as"); //使用Matcher进行各种查找替换操作 Matcher m = p.matcher(str); int i = 0; while(m.find()){ i++; } System.out.println(i);
------解决方案--------------------