gpt4 book ai didi

java - 如何编写递归方法来返回包含 token 字符串的文件中的所有行

转载 作者:行者123 更新时间:2023-12-02 07:12:44 24 4
gpt4 key购买 nike

我的教授给我们布置了一项作业,要求我们编写一个可以执行很多操作的程序。该程序具体执行的一件事是遍历 .txt 文件,并返回您指定的单词的所有实例以及它们所在的行。例如,如果这是文本文件:

This is a test.
Testing the word file.
This will be considered a test.

运行该方法并搜索单词“test”后,您应该收到类似以下内容:

1: This is a test.       
3: This will be considered a test.

现在这是我的问题。他希望我们用递归方法来做,但我不知道如何启动该方法。我知道对于递归方法,您必须调用自身并在每次调用它时进行归约,但是,该方法的参数是一个单词。假设我有:

String getTheWord (String word) {     
if (word == 0){ //which still wouldn't compile, so I think I should use word == null
// something
}

//something smart here

return getTheWord(word - 1); // which wouldn't compile
}

那么我该怎么写呢?我认为我必须使用字符串作为参数,否则我怎么知道我要查找的单词是什么?或者也许我错了,任何事情都有帮助!

最佳答案

尝试如下:

public String getTheWord(String textToSearch, String searchingFor,
int currentLineNumber) {

// Separate the text into lines.
String[] lines = textToSearch.split('\n');

// Get the first line of the (remaining) text.
String firstLine = lines[0];

// We're going to have some result from this method call: either
// an empty string or a message indicating that we found the word.
String resultFromThisLine = "";

// Now, look for the word.
if (firstLine.contains(searchingFor)) {
// We found it.
resultFromThisLine = currentLineNumber + ": " + firstLine + "\n";
}

// Now we check to see if there are any lines left.
if (lines.length == 1) {
// This was the last line.
return resultFromThisLine;
} else {
// There are more line(s).
// Create a string with all lines but the first one.
String remainingLines = "";
for (int i=1; i<lines.length; i++) {
remainingLines += lines[i] + "\n";
}


// Here's the key part.
// Take the result from this line, add it to the result from the
// next line, and return *that*.

return resultFromThisLine + getTheWord(remainingLines, searchingFor,
currentLine + 1);

}
}

关于java - 如何编写递归方法来返回包含 token 字符串的文件中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15317869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com