Java 将长字符串拆分为单个单词,以进入二叉树
因此,我目前正在将一个文本文件读入我的程序中,该文件被分解成单个单词,并存储在二叉树中 到目前为止,我已经将我的文本文件转换成一个字符串,然后修改该字符串以删除所有标点符号,并使所有内容都小写(我被指示这样做)。我现在很难找到一种方法将我庞大的字符串分解成单个单词,然后需要将这些单词插入到二叉树中 这是我的密码Java 将长字符串拆分为单个单词,以进入二叉树,java,string,text-files,Java,String,Text Files,因此,我目前正在将一个文本文件读入我的程序中,该文件被分解成单个单词,并存储在二叉树中 到目前为止,我已经将我的文本文件转换成一个字符串,然后修改该字符串以删除所有标点符号,并使所有内容都小写(我被指示这样做)。我现在很难找到一种方法将我庞大的字符串分解成单个单词,然后需要将这些单词插入到二叉树中 这是我的密码 public class Tester { //Start the program public static void main(String[] args) throws File
public class Tester {
//Start the program
public static void main(String[] args) throws FileNotFoundException {
Tester run = new Tester();
run.it();
}
//run Program step by step
public void it() throws FileNotFoundException {
BTree theTree = new BTree();
this.readInFile();
theTree.print();
}
//Read file into string
public String readInFile() throws FileNotFoundException {
String myFile = "";
int numWords = 0;
Scanner myScan = new Scanner(new File("Dracula.txt"));
while(myScan.hasNext() == true) {
myFile += myScan.nextLine();
}
return myFile;
}
//delete punctuation make all letters lowercase
public String stripPunctuation(String myFile) {
myFile.replace('.', ' ');
myFile.replace(',', ' ');
myFile.replace('!', ' ');
myFile.replace('?', ' ');
myFile.replace('(', ' ');
myFile.replace(')', ' ');
myFile.replace('"', ' ');
myFile.replace('[', ' ');
myFile.replace(']', ' ');
myFile.toLowerCase();
return myFile;
}
//here is where i want to break up the string and add each word to my binary tree
public BTree fillTree(String myFile) {
BTree thisTree = new BTree();
while()
return thisTree;
}
}
我在想while循环可能会有所帮助,但我不确定如何逐字符扫描字符串以正确地将其分开。使用:
split()
使用正则表达式确定输入的哪一部分是分隔符。regex\s+/code>表示“1个或多个空白字符”
另外,您的代码中有一个bug。这一行:
myFile += myScan.nextLine();
将具有将一行的最后一个字与下一行的第一个字连接在一起的效果。解决此问题的最小更改是:
myFile += myScan.nextLine() + " ";
myFile += myScan.nextLine() + " ";