[英]reading from text file to string array
所以我可以在我的文本文件中搜索一個字符串,但是,我想在這個ArrayList中對數據進行排序並實現一個算法。 是否可以從文本文件中讀取文本文件中的[Strings]值存儲在String []數組中。
也可以將字符串分開嗎? 而不是我的數組有:
[Alice was beginning to get very tired of sitting by her sister on the, bank, and of having nothing to do:]
是否可以將數組作為:
["Alice", "was" "beginning" "to" "get"...]
。
public static void main(String[]args) throws IOException
{
Scanner scan = new Scanner(System.in);
String stringSearch = scan.nextLine();
BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
List<String> words = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
for(String sLine : words)
{
if (sLine.contains(stringSearch))
{
int index = words.indexOf(sLine);
System.out.println("Got a match at line " + index);
}
}
//Collections.sort(words);
//for (String str: words)
// System.out.println(str);
int size = words.size();
System.out.println("There are " + size + " Lines of text in this text file.");
reader.close();
System.out.println(words);
}
也可以將字符串分開嗎? 是的,您可以使用此分隔字符串作為空格。
String[] strSplit;
String str = "This is test for split";
strSplit = str.split("[\\s,;!?\"]+");
此外,您還可以逐字閱讀文本文件。
Scanner scan = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("Your File Path")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(scan.hasNext()){
System.out.println( scan.next() );
}
要將一行拆分為一個單詞數組,請使用:
String words = sentence.split("[^\\w']+");
正則表達式[^\\w']
表示“不是單詞char或撇號”
這將捕獲帶有“can can”等嵌入式撇號的單詞,並跳過所有標點符號。
注釋已經提出了解析報字的邊緣情況下,如'this'
為this
。
這是解決方案 - 您必須先刪除包裝引號:
String[] words = input.replaceAll("(^|\\s)'([\\w']+)'(\\s|$)", "$1$2$3").split("[^\\w']+");
這是一些邊緣和角落情況的測試代碼:
public static void main(String[] args) throws Exception {
String input = "'I', ie \"me\", can't extract 'can't' or 'can't'";
String[] words = input.replaceAll("(^|[^\\w'])'([\\w']+)'([^\\w']|$)", "$1$2$3").split("[^\\w']+");
System.out.println(Arrays.toString(words));
}
輸出:
[I, ie, me, can't, extract, can't, or, can't]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.