用Java写一个程序,从文件(c:\test.txt)中查出字符串”mobnet”出现的次数?
3个回答
展开全部
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TxtCount {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt"));
StringBuilder sb = new StringBuilder();
while (true) {
String str = br.readLine();
if (str == null)
break;
sb.append(str);
}
Pattern p = Pattern.compile("mobnet");
Matcher m = p.matcher(sb);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("mobnet一共出现了" + count + "次");
}
}
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TxtCount {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt"));
StringBuilder sb = new StringBuilder();
while (true) {
String str = br.readLine();
if (str == null)
break;
sb.append(str);
}
Pattern p = Pattern.compile("mobnet");
Matcher m = p.matcher(sb);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("mobnet一共出现了" + count + "次");
}
}
展开全部
import java.io.*;
public class StringMatch {
public static void main(String args[]) {
int count = 0;
try {
FileReader in = new FileReader("C:/test.txt");
BufferedReader br = new BufferedReader(in);
String str = br.readLine();
// System.out.println(str);
while (str != null) {
String sToFind = "mobnet";
int index = -1;
while (str.indexOf(sToFind) != -1) {
index = str.indexOf(sToFind) + sToFind.length();
str = str.substring(index);
count++;
}
str = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(count);
}
}
写得比较粗糙! 见谅!
public class StringMatch {
public static void main(String args[]) {
int count = 0;
try {
FileReader in = new FileReader("C:/test.txt");
BufferedReader br = new BufferedReader(in);
String str = br.readLine();
// System.out.println(str);
while (str != null) {
String sToFind = "mobnet";
int index = -1;
while (str.indexOf(sToFind) != -1) {
index = str.indexOf(sToFind) + sToFind.length();
str = str.substring(index);
count++;
}
str = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(count);
}
}
写得比较粗糙! 见谅!
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
用正则匹配一下,最后能得到匹配集合中元素的个数;
在.net 中是这个思路,java也应该是大同小异吧
在.net 中是这个思路,java也应该是大同小异吧
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询