gpt4 book ai didi

c# - 我需要帮助在 C# 中显示文本文件中的单词(字符串)

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:14 24 4
gpt4 key购买 nike

我需要帮助在控制台应用程序中显示文本文件中的单词。例如,我的输入字符串是“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);
}
}
}

输出如下:

Output Snapshot

有人可以帮忙吗?

最佳答案

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

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

此代码段使用您的代码(变量)。要创建我们的标记,我们必须拆分当前行,为此我们使用了 String.Split

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

关于c# - 我需要帮助在 C# 中显示文本文件中的单词(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34013044/

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