1.要求:查找最长单词链
2.思想:首先读取文本文件,然后赋值给字符数组,然后进行后一个单词的首字母和前边的尾字母比对,如果相同则把后边的单词赋值给前边的,如果不同,继续向后搜索,最后循环输出赋值的字符数组,输出到文本文件;
3.源代码:
package 频率; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; public class zuichang { // public void zimuss() throws Exception{ public static void main(String args[]) throws IOException { try { BufferedReader br = new BufferedReader(new FileReader("C:\Users\LJM\Desktop\a.txt")); StringBuffer sb = new StringBuffer(); String text =null; while ((text=br.readLine())!= null){ sb.append(text);// 将读取出的字符追加到stringbuffer中 } br.close(); // 关闭读入流 String str = sb.toString().toLowerCase(); // 将stringBuffer转为字符并转换为小写 String[] words = str.split("[^(a-zA-Z)]+"); // 非单词的字符来分割,得到所有单词 int i = 1; String[] sortStr = new String[words.length]; sortStr[0] = words[0]; for (int j = 0; j < words.length; j++) { if (sortStr[i - 1].equals(words[j])) continue; if (sortStr[i - 1].charAt(sortStr[i - 1].length() - 1) == words[j].charAt(0)) { sortStr[i] = words[j]; i++; } } File f = new File("C:\Users\LJM\Desktop\b.txt"); //用FileOutputSteam包装文件,并设置文件可追加 OutputStream out = new FileOutputStream(f,true); //字符数组 for( i = 0 ; i < sortStr.length ; i++ ) { if(sortStr[i]!=null) { out.write(sortStr[i].getBytes()); //向文件中写入数据 out.write(' '); // 表示换行 out.write(' '); } else if(sortStr[i]==null) { System.out.println(" "); } } out.close(); //关闭输出流 System.out.println("写入成功!"); // for (String s : sortStr) { // System.out.print(s+","); // } //System.out.println(); }catch (Exception e) { e.printStackTrace(); } } }
4.截图: