2011-03-04 110 views
0

需要一些幫助來創建文件和字符串搜索引擎。 該程序需要讓用戶輸入文件的名稱,然後輸入搜索字符串的名稱打印搜索結果文件,將其存儲,然後詢問用戶是否需要其他選擇。 這是我到目前爲止有:字符串/文件搜索引擎

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; 


     } 
    } 
} 

我在編程垃圾所以保持它的簡單與術語的xD

+1

請更正您的格式:) – Aidiakapi 2011-03-04 12:51:07

+2

您的問題是什麼? – Gabe 2011-03-04 12:52:05

+0

好吧,你打算打開一個指定的文件,搜索一行文本,然後你會輸出到輸出文件到底是什麼? – Purplegoldfish 2011-03-04 13:02:38

回答

1

我真的不知道你想要什麼,但如果你要搜索的字符串的所有出現一個文件,並希望返回的位置(行和列),那麼這可能有所幫助:

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); 
     } 
    } 
} 
+0

這幾乎是正確的,只需將結果存儲到另一個文件 – Katashi 2011-03-04 14:11:09

+0

這幾乎是它只需要然後將結果存儲到另一個文件也在行中 - 私有靜態無效Pause(字符串動作=「繼續」) - 有一個錯誤的等於它說默認參數說明符是不允許的D;我不是這方面的專家 – Katashi 2011-03-04 14:17:10

+0

默認參數是C#4.0中的一個新函數,要解決該問題,只需刪除'=「continue」'部分。我更新了代碼,將其輸出寫入out.txt,並且刪除了默認參數。 – Aidiakapi 2011-03-04 14:55:36

0

嗯,其實我不明白你在問什麼。你是否試圖在指定的文件中搜索一些文本,然後寫出文本的位置?

如果是嘗試看看這個:

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(); 
} 
+0

不是在哪裏但文本是什麼,並將其寫入屏幕和一個單獨的文件,然後循環結束以查看用戶是否想要繼續 – Katashi 2011-03-04 16:23:26