我有一个程序可以在文本文件中查找单词并将其打印出来。但这是一项学校作业,我需要使用一定程度的面向对象编程,比如使用不同的类和接口。
所以,我遇到的问题是我有两个公共类,在主类中调用和采用时,使用main方法打印出我想要的两个字符串值。
代码看起来像这样
public class GetFilePath
{
public string FilePath;
public GetFilePath(string fn)
{
/// string path = "testfile.txt";
FilePath = fn;
}
public void SetFilename(string NewFilePath)
{
FilePath = NewFilePath;
}
}
public class GetSearchWord
{
public string WordSearch;
public GetSearchWord(string st)
{
WordSearch = st;
}
public void SetSearchTerm(string NewSearchTerm)
{
WordSearch = NewSearchTerm;
}
}
这些在主函数中实现如下
Console.Write("please enter a file to search for: ");
// Call the constructor that has no parameters.
GetFilePath Filepath1 = new GetFilePath("");
Console.WriteLine(Filepath1.FilePath);
Filepath1.SetFilename("testfile.txt");
Console.WriteLine(Filepath1.FilePath);
// Call the constructor that has one parameter.
Console.Write("please enter a word to search for in the file: ");
GetSearchWord SearchedWord1 = new GetSearchWord("");
Console.WriteLine(SearchedWord1.WordSearch);
SearchedWord1.SetSearchTerm("true");
Console.WriteLine(SearchedWord1.WordSearch);
但我需要将Filepath1.FilePath
和SearchedWord1.WordSearch
连接到以下字符串
string FilePath = "";
string WordSearch = "";
正如你所看到的那些目前是空的。
这是我的搜索功能中的关键字符串,它实际上用单词!
搜索这些行FilePath和WordSearched字符串用作以下
using (StreamReader fs = File.OpenText(FilePath))
{
int count = 0; //counts the number of times wordResponse is found.
int lineNumber = 0;
while (!fs.EndOfStream)
{
string line = fs.ReadLine();
lineNumber++;
int position = line.IndexOf(WordSearch);
if (position != -1)
{
count++;
Console.WriteLine("Match#{0} line {1}: {2}", count, lineNumber, line);
}
}
if (count == 0)
{
Console.WriteLine("your word was not found!");
}
else
{
Console.WriteLine("Your word was found " + count + " times!");
}
Console.WriteLine("Press enter to quit.");
Console.ReadKey();
}
我尝试过做的是设置
string WordSearch = SearchedWord1.WordSearch;
作为我想要实现的一个例子,SearchedWord1.WordSearch目前设置为“true”,这是我想要搜索我的文件的关键字。
答案 0 :(得分:1)
如果我正确理解了您的问题,那么以下代码可以解决您的问题(使用以下内容更新您的主要代码):
Console.Write("please enter a file to search for: ");
// Call the constructor that has no parameters.
var filePathInput = Console.ReadLine();
GetFilePath Filepath1 = new GetFilePath(filePathInput);
Console.WriteLine(Filepath1.FilePath);
Filepath1.SetFilename("testfile.txt");
Console.WriteLine(Filepath1.FilePath);
// Call the constructor that has one parameter.
Console.Write("please enter a word to search for in the file: ");
var searchWordInput = Console.ReadLine();
GetSearchWord SearchedWord1 = new GetSearchWord(searchWordInput);
Console.WriteLine(SearchedWord1.WordSearch);
SearchedWord1.SetSearchTerm("true");
Console.WriteLine(SearchedWord1.WordSearch);
更改是此代码从用户那里获得输入...