如何在文本文件中找到一个单词,然后将前一个单词添加到该单词中? [英] How do I find a word in a text file and then get the previous word to that one?
本文介绍了如何在文本文件中找到一个单词,然后将前一个单词添加到该单词中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,我正在寻找一个单词,但我需要在我正在搜索的单词之前的单词。例如Patrick Called。我要搜索的常用词是Called,但我想要回归Patrick。我目前正在使用Streamreader,但卡住
I have a text file where I am looking for a word however I need the word prior to one I am searching for. For example "Patrick Called". The common word that I would search for is Called, but I want to return Patrick. I am currently using Streamreader but am stuck
推荐答案
试试这个:
Try this:
string fileText = File.ReadAllText("yourFile.txt");
string[] words = fileText.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // this splits the string and makes sure that there are no empty strings in the array
int wordIndex = Array.IndexOf(words, "Called");
if (wordIndex > 0)
{
string str = words[wordIndex - 1];
Console.WriteLine(str); // this will print 'Patrick' if the file contains 'Patrick Called'
}
else
{
// the searched word is the first word; you can't get the word before it
// OR: the searched word doesn't exist
}
希望这会有所帮助。
Hope this helps.
HI
在< i style =color:red> ProgramFox 解决方案。
使用StreamReader
试试这个,这将读取与定义的单词匹配的所有名称
..
HI On top of ProgramFox solution.
try this usingStreamReader
, this willread all the names
matching the defined word..
class Program
{
static void Main(string[] args)
{ //ƒ
string file = @"D:\Projects\console_poc\console_poc\text.txt";
// input as below
//Patrik Called something.. john Called
//some test test test karthik Called .....
using (StreamReader sr = new StreamReader(file))
{
String line = sr.ReadToEnd();
string[] array = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string key = "Called";
for (int i = 1; i < array.Length; i++)
{
if (array[i] == key)
Console.WriteLine(array[i - 1]);
// output as below:
// Patrik
// john
// karthik
}
}
Console.ReadLine();
}
}
这是解决方案之一。
fileText.Split(new char [] {'','\ n','。'}
这个词在行的末尾,用空格分割不行。所以也加上'\ n'。
This is an add on for solution one.
fileText.Split(new char[] { ' ', '\n', '.' }
When the word is on the end of the line the split with a space wont work. So also add '\n'.
这篇关于如何在文本文件中找到一个单词,然后将前一个单词添加到该单词中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文