【问题标题】:I need help displaying a word (string) from a text file in C#我需要帮助在 C# 中显示文本文件中的单词(字符串)
【发布时间】:2015-12-01 05:10:54
【问题描述】:

在控制台应用程序中显示文本文件中的单词时,我需要帮助。例如,我的输入字符串是“the”,代码将读取文本文件并输出包含“the”的单词,例如“The”和“father”。我已经准备好了代码,但它输出了整个句子,包括单词而不是单词本身。代码如下所示:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace QuizTakeHome
{
    class Program
    {
        static void Main(string[] args)
        {
            string line;
            int counter = 0;

            Console.WriteLine("Enter a word to search for: ");
            string userText = Console.ReadLine();

            string file = "Gettysburg.txt";
            StreamReader myFile = new StreamReader(file);

            int found = 0;

            while ((line = myFile.ReadLine()) != null)
            {
                counter++;
                int index = line.IndexOf(userText, StringComparison.CurrentCultureIgnoreCase);
                if (index != -1)
                {
                    //Since we want the word that this entry is, we need to find the space in front of this word
                    string sWordFound = string.Empty;
                    string subLine = line.Substring(0, index);
                    int iWordStart = subLine.LastIndexOf(' ');
                    if (iWordStart == -1)
                    {
                        //If there is no space in front of this word, then this entry begins at the start of the line
                        iWordStart = 0;
                    }

                    //We also need to find the space after this word
                    subLine = line.Substring(index);
                    int iTempIndex = subLine.LastIndexOf(' ');
                    int iWordLength = -1;
                    if (iTempIndex == -1)
                    {    //If there is no space after this word, then this entry goes to the end of the line.
                        sWordFound = line.Substring(iWordStart);
                    }
                    else
                    {
                        iWordLength = iTempIndex + index - iWordStart;
                        sWordFound = line.Substring(iWordStart, iWordLength);

                    }

                    Console.WriteLine("Found {1} on the sentence: {1} on line number: {0}", counter, sWordFound, line);
                    found++;
                }
            }
            Console.WriteLine("A total of {0} occurences found", found);
        }
    }
   }

输出如下:

有人可以帮忙吗?

【问题讨论】:

  • 好吧,您逐行读取文件,并在整个行中搜索匹配项。您应该逐字阅读文件,或拆分行,然后执行 IndexOf
  • 你觉得你能告诉我这是怎么做的吗?
  • 嗯,首先你需要确定什么是“单词”。单词可以用空格分隔,也可以用其他字符、逗号、分号等分隔。我们在这里看什么样的输入?
  • 我的输入字符串是“the”。我已准备好一切,但我的 sWordFound 输出的是“the”,但之后是句子的其余部分。我只需要剪掉“the”之后的部分。

标签: c# regex console


【解决方案1】:

您可以从您的句子中创建标记并检查每个标记:

found = 0;
String[] tokens = line.Split(new char[] {' '});
foreach (String token in tokens) {
    if (token.IndexOf(userText, StringComparison.OrdinalIgnoreCase) != -1) {
        Console.WriteLine(token); // Do your stuff here
        found++; //increment to know how many times you found the word in the current line
    }
}
counter += found; //counter will contains all occurences in lines

这个 sn-p 使用你的代码(变量)。 要创建我们的令牌,我们必须拆分当前行,为此我们使用了String.Split

我认为这是没有正则表达式函数的最佳方法。 希望对你有帮助。

【讨论】:

  • 嘿,您的代码有效。但是我如何计算我的输入字符串出现在您的代码中的次数?
  • Nvm,我明白了。非常感谢您的代码。那我还需要剩下的代码吗?那我就不需要使用我的while循环了吧?
  • 我对其进行了编辑以帮助您更多。你必须保留你的循环,但你必须用 sn-p 替换你的 while 循环中的代码。希望对你有帮助。
  • 是的,我明白了。谢谢你:)
【解决方案2】:

您的Console.WriteLine 错误。

使用这个:

Console.WriteLine("Found {1} on the sentence: {2} on line number: {0}", counter, userText, sWordFound);

【讨论】:

    【解决方案3】:

    这是执行此操作的代码。请记住,还有许多其他方法。

        var myfilter = "the";
        var lines = File.ReadAllLines(@"C:\myfile.txt");
        var wordsCsv = lines.Select(l => l.Split(new[] { ' ' }).Where(w => w.ToLower().Contains(myfilter.ToLower()))).Where(w => w.Any()).Aggregate("", (current, wordsList) => current + "," + string.Join(",", wordsList));
    

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多