本文介绍了如何在文本文件中找到一个单词,然后将前一个单词添加到该单词中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个文本文件,我正在寻找一个单词,但我需要在我正在搜索的单词之前的单词。例如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推荐答案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 arrayint 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.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(); } } 这篇关于如何在文本文件中找到一个单词,然后将前一个单词添加到该单词中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-13 16:11