首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#中的字符串操作

C#中的字符串操作
EN

Stack Overflow用户
提问于 2017-01-05 20:57:16
回答 0查看 141关注 0票数 0

我有一个在文本文件中查找单词并将其打印出来的程序。但这是一个学校作业,我需要使用一定程度的面向对象编程,比如使用不同的类和接口。

所以,我的问题是,我有两个公共类,当在主类中调用和采用时,使用main方法,打印出我想要的两个字符串值。

代码如下所示

代码语言:javascript
复制
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;
    }
}

这些实现到main函数中,如下所示

代码语言:javascript
复制
        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.FilePathSearchedWord1.WordSearch连接到以下字符串

代码语言:javascript
复制
string FilePath = "";
string WordSearch = "";

正如你所看到的,目前这些都是空的。

它们是我的搜索函数中的关键字符串,它实际上是搜索包含单词的行!

FilePath和WordSearched字符串的用法如下

代码语言:javascript
复制
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();
        }

我尝试做的是设置

代码语言:javascript
复制
string WordSearch = SearchedWord1.WordSearch;

例如,SearchedWord1.WordSearch当前设置为"true“,这是我想要搜索文件的关键字。

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41485730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档