计算最长英语单词链
這是鄒欣老師一篇博文的內容,當時有幸可以看到,今天又被老師作為隨堂練測試來進行練習.
這是原文的地址:《計算最長英語單詞鏈》 https://www.cnblogs.com/xinz/p/7119695.html
?
一、需求分析
老師給我們的要求是:一個文本文件中有N 個不同的英語單詞,將首字母和尾字母相同單詞進行拼接,然后輸出相應的字符串.
例如有以下單詞:
?
Apple
?
Zoo
?
Elephant
?
Under
?
Fox
?
Dog
?
Moon
?
Leaf
?
Tree
?
?
拿到這個問題的之后,首先想到的就是對問題進行分解.我們可以將它分為四個部分:讀取文件,將單詞首尾字母取出,進行比對并存入數組,寫入文件.
?
二、具體實現
首先,我們是要從文件將內容讀取出來,,這個是比較容易的.以下代碼可以實現.
?
1 File file = new File("E://JAVA//軟件工程//WordsLines//input1.txt"); 2 ArrayList<String> arrayList = new ArrayList<>(); 3 try { 4 // int i = 0; 5 InputStreamReader inputReader = new InputStreamReader(new FileInputStream(file)); 6 BufferedReader bf = new BufferedReader(inputReader); 7 8 // 按行讀取字符串 9 String str; 10 while ((str = bf.readLine()) != null) { 11 arrayList.add(str); 12 // i++; 13 } 14 // if (i == 0) {//判斷文本為空 15 // System.out.println("文本文件為空"); 16 // System.out.println("程序運行出錯,程序結束"); 17 // System.exit(0); 18 // } 19 // if (i == 1) {//判斷只有單個單詞 20 // System.out.println("文件單詞只有一個"); 21 // System.out.println("程序運行出錯,程序結束"); 22 // System.exit(0); 23 // } 24 bf.close(); 25 inputReader.close(); 26 } catch (IOException e) { 27 e.printStackTrace(); 28 } 29 // 對ArrayList中存儲的字符串進行處理 30 String[] array = new String[arrayList.size()]; 31 for (int i = 0; i < arrayList.size(); i++) { 32 array[i] = arrayList.get(i); 33 } 34 // for (int i = 0; i < length; i++) { 35 // System.out.println(array[i] + "\n"); 36 // }?
?
在讀取到文件內容并存儲到數組中后,我們要將各個單詞中的收尾字母取出.在JAVA中(JavaScript),提供了subString方法,使我們可以提取字符串中介于兩個指定下標之間的字符,這就給我們一個很好的方法去提取每個單詞中的字符了.但是需要注意的是,在subString中是不可以接收負的參數的.關于他的使用方法,可以參考JavaScript substring() 方法.
那么我們就可以對他進行操作了.
通過 1 array[i].length() - 1, array[i].length() 的范圍來找到單詞中的最后一個字母,通過 1 array[j].substring(0, 1) 的范圍來找到單詞中的第一個字母.然后通過比對將他們存入數組.
1 String a, b, str; 2 String[] strresult = new String[arrayList.size()]; 3 for (int i = 0; i < arrayList.size(); i++) { 4 str = array[i]; 5 a = array[i].substring(array[i].length() - 1, array[i].length()); 6 for (int j = 0; j < arrayList.size(); j++) { 7 b = array[j].substring(0, 1); 8 if (array[i].equals(array[j]) == false && a.equals(b)) { 9 str = str + array[j]; 10 a = array[j].substring(array[j].length() - 1, array[j].length()); 11 } 12 b = null; 13 } 14 strresult[i] = str; 15 }?
存入數組后,將所得的數組中的各字符長度看做一維數組進行排序,得到字符串長度最長的字符串就是最長英語單詞鏈了.
1 int max = strresult[0].length(); 2 String result = strresult[0]; 3 for (int i = 1; i < strresult.length; i++) { 4 if (strresult[i].length() > max) { 5 max = strresult[i].length(); 6 result = strresult[i]; 7 } 8 }?
最后將得到的strresult數組中的內容存入文本文件就可以了.
?截圖;
?
三、思考
最基本的方法就是這么簡單,但是,如果我們遇到了一個超大的英文文本,或者是超大的英文文章該怎么辦呢?會不會程序崩潰?會不會出現溢出?
又或者是當我們儲存的文本過小,又會出現什么情況呢?
再或者是當我們輸入的內容不只是英文,存在其他的語言,比如漢語,數字呢?
這些都是值得思考的問題.
?
轉載于:https://www.cnblogs.com/yandashan666/p/10987036.html
總結
- 上一篇: 如何批量在多个文件夹名称前面加上年份、月
- 下一篇: 鱼的备忘录