C# 字符串/文件搜索引擎
需要一些帮助来创建一个文件和字符串搜索引擎。 程序需要让用户输入文件名,然后输入搜索字符串的名称,打印搜索结果文件,存储它,然后询问用户是否需要其他选择。 这就是我到目前为止所做的:C# 字符串/文件搜索引擎,c#,C#,需要一些帮助来创建一个文件和字符串搜索引擎。 程序需要让用户输入文件名,然后输入搜索字符串的名称,打印搜索结果文件,存储它,然后询问用户是否需要其他选择。 这就是我到目前为止所做的: using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; public class SwitchTest { priva
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
public class SwitchTest
{
private const int tabSize = 4;
private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
public static void Main(string[] args)
{
string userinput;
Console.WriteLine("Please enter the file to be searched");
userinput = Console.ReadLine();
using (StreamReader reader = new StreamReader("test.txt"))
{
//Read the file into a stringbuilder
StringBuilder sb = new StringBuilder();
sb.Append(reader.ReadToEnd());
Console.ReadLine();
}
{
StreamWriter writer = null;
if (args.Length < 2)
{
Console.WriteLine(usageText);
return;
}
try
{
// Attempt to open output file.
writer = new StreamWriter(args[1]);
// Redirect standard output from the console to the output file.
Console.SetOut(writer);
// Redirect standard input from the console to the input file.
Console.SetIn(new StreamReader(args[0]));
}
catch (IOException e)
{
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
return;
}
writer.Close();
// Recover the standard output stream so that a
// completion message can be displayed.
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine("COMPLETE!", args[0]);
return;
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用System.Text.RegularExpressions;
使用System.IO;
公共类交换测试
{
private const int tabSize=4;
private const string usageText=“用法:INSERTTABS inputfile.txt outputfile.txt”;
公共静态void Main(字符串[]args)
{
字符串用户输入;
Console.WriteLine(“请输入要搜索的文件”);
userinput=Console.ReadLine();
使用(StreamReader=newstreamreader(“test.txt”))
{
//将文件读入stringbuilder
StringBuilder sb=新的StringBuilder();
sb.Append(reader.ReadToEnd());
Console.ReadLine();
}
{
StreamWriter=null;
如果(参数长度<2)
{
控制台写入线(usageText);
返回;
}
尝试
{
//尝试打开输出文件。
writer=newstreamwriter(args[1]);
//将标准输出从控制台重定向到输出文件。
控制台。放样(编写器);
//将标准输入从控制台重定向到输入文件。
Console.SetIn(新的StreamReader(args[0]);
}
捕获(IOE异常)
{
TextWriter errorWriter=控制台。错误;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
返回;
}
writer.Close();
//恢复标准输出流,以便
//可以显示完成消息。
StreamWriter standardOutput=新的StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush=true;
控制台放样(标准输出);
Console.WriteLine(“COMPLETE!”,args[0]);
返回;
}
}
}
我在编程方面一窍不通,所以用xD这个术语保持简单其实我还不明白你在问什么。您是否试图在指定文件中搜索某些文本,然后写出文本的位置 如果是,请尝试查看以下内容:
while (true)
{
Console.Write("Path: ");
string path = Console.ReadLine();
Console.Write("Text to search: ");
string search = Console.ReadLine();
if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(search))
{
break;
}
if (!File.Exists(path))
{
Console.WriteLine("File doesn't exists!");
continue;
}
int index = File.ReadAllText(path).IndexOf(search);
string output = String.Format("Searched Text Position: {0}", index == -1 ? "Not found!" : index.ToString());
File.WriteAllText("output.txt", output);
Console.WriteLine("Finished! Press enter to continue...");
Console.ReadLine();
Console.Clear();
}
我真的不知道您想要什么,但是如果您想要搜索一个文件以查找字符串的所有发生情况,并且想要返回位置(行和列),那么这可能会有所帮助:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace CS_TestApp
{
class Program
{
struct Occurrence
{
public int Line { get; set; }
public int Column { get; set; }
public Occurrence(int line, int column) : this()
{
Line = line;
Column = column;
}
}
private static string[] ReadFileSafe(string fileName)
{
// If the file doesn't exist
if (!File.Exists(fileName))
return null;
// Variable that stores all lines from the file
string[] res;
// Try reading the entire file
try { res = File.ReadAllLines(fileName, Encoding.UTF8); }
catch (IOException) { return null; }
catch (ArgumentException) { return null; }
return res;
}
private static List<Occurrence> SearchFile(string[] file, string searchString)
{
// Create a list to store all occurrences of substring in the file
List<Occurrence> occ = new List<Occurrence>();
for (int i = 0; i < file.Length; i++) // Loop through all lines
{
string line = file[i]; // Save the line
int totalIndex = 0; // The total index
int index = 0; // The relative index (the index found AFTER totalIndex)
while (true) // Loop until breaks
{
index = line.IndexOf(searchString); // Search for the index
if (index >= 0) // If a string was found
{
// Save the occurrence to our list
occ.Add(new Occurrence(i, totalIndex + index));
totalIndex += index + searchString.Length; // Add the total index and the searchString
line = line.Substring(index + searchString.Length); // Cut of the searched part
}
else break; // If no more occurances found
}
}
// Here we have our list filled up now we can return it
return occ;
}
private static void PrintFile(string[] file, List<Occurrence> occurences, string searchString)
{
IEnumerator<Occurrence> enumerator = occurences.GetEnumerator();
enumerator.MoveNext();
for (int i = 0; i < file.Length; i++)
{
string line = file[i];
int cutOff = 0;
do
{
if (enumerator.Current.Line == i)
{
Console.Write(line.Substring(0, enumerator.Current.Column - cutOff));
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(searchString);
Console.ResetColor();
line = line.Substring(enumerator.Current.Column + searchString.Length - cutOff);
cutOff = enumerator.Current.Column + searchString.Length;
}
else break;
}
while (enumerator.MoveNext());
Console.WriteLine(line); // Write the rest
}
}
private static bool WriteToFile(string file, List<Occurrence> occ)
{
StreamWriter sw;
try { sw = new StreamWriter(file); }
catch (IOException) { return false; }
catch (ArgumentException) { return false; }
try
{
foreach (Occurrence o in occ)
{
// Write all occurences
sw.WriteLine("(" + (o.Line + 1).ToString() + "; " + (o.Column + 1).ToString() + ")");
}
return true;
}
finally
{
sw.Close();
sw.Dispose();
}
}
static void Main(string[] args)
{
bool anotherFile = true;
while (anotherFile)
{
Console.Write("Please write the filename of the file you want to search: ");
string file = Console.ReadLine();
Console.Write("Please enter the string to search for: ");
string searchString = Console.ReadLine();
string[] res = ReadFileSafe(file); // Call our search method
if (res == null) // If it either couldn't open the file, or the file didn't exist
Console.WriteLine("Couldn't open the read file.");
else // If the file was opened
{
Console.WriteLine();
Console.WriteLine("File:");
Console.WriteLine();
List<Occurrence> occ = SearchFile(res, searchString); // Search the file
PrintFile(res, occ, searchString); // Print the result
Console.WriteLine();
Console.Write("Please enter the file you want to write the output to: ");
file = Console.ReadLine();
if (!WriteToFile(file, occ))
Console.WriteLine("Couldn't write output.");
else
Console.WriteLine("Output written to: " + file);
Console.WriteLine();
}
Pause("continue");
requestAgain:
Console.Clear();
Console.Write("Do you want to search another file (Y/N): ");
ConsoleKeyInfo input = Console.ReadKey(false);
char c = input.KeyChar;
if(c != 'y' && c != 'Y' && c != 'n' && c != 'N')
goto requestAgain;
anotherFile = (c == 'y' || c == 'Y');
if(anotherFile)
Console.Clear();
}
}
private static void Pause(string action)
{
Console.Write("Press any key to " + action + "...");
Console.ReadKey(true);
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.IO;
命名空间CS_TestApp
{
班级计划
{
结构发生
{
公共整数行{get;set;}
公共int列{get;set;}
公共事件(int行,int列):this()
{
直线=直线;
列=列;
}
}
私有静态字符串[]ReadFileSafe(字符串文件名)
{
//如果文件不存在
如果(!File.Exists(fileName))
返回null;
//存储文件中所有行的变量
字符串[]res;
//尝试读取整个文件
试试{res=File.ReadAllLines(文件名,Encoding.UTF8);}
catch(IOException){returnnull;}
catch(ArgumentException){returnnull;}
返回res;
}
私有静态列表搜索文件(字符串[]文件,字符串搜索字符串)
{
//创建一个列表以存储文件中所有出现的子字符串
列表occ=新列表();
for(int i=0;i=0)//如果找到字符串
{
//将事件保存到我们的列表中
occ.Add(新事件(i,总索引+索引));
totalIndex+=index+searchString.Length;//添加总索引和searchString
line=line.Substring(index+searchString.Length);//搜索部分的剖切
}
else break;//如果找不到其他事件
}
}
//我们的名单填好了,现在我们可以退了
返回occ;
}
私有静态void打印文件(字符串[]文件,列表发生,字符串搜索字符串)
{
IEnumerator枚举器=发生。GetEnumerator();
枚举数。MoveNext();
for(int i=0;i