代码之家  ›  专栏  ›  技术社区  ›  SmartestVEGA

如何找到字符串模式并使用C从文本文件打印它#

  •  4
  • SmartestVEGA  · 技术社区  · 15 年前

    我有一个带有字符串“abcdef”的文本文件

    我想在我的测试文件中搜索字符串“abc”…然后为abc打印下两个字符。这里是“de”。

    我怎样才能完成? 哪个级别和功能?

    4 回复  |  直到 15 年前
        1
  •  3
  •   Steven    15 年前

    试试这个:

    string s = "abcde";
    int index = s.IndexOf("abc");
    if (index > -1 && index < s.Length - 4)
        Console.WriteLine(s.SubString(index + 3, 2));
    

    更新:Tanascius注意到一个错误。我把它修好了。

        2
  •  3
  •   thelost    15 年前

    一行一行地阅读你的文件,使用如下:

    string line = "";
    
    if line.Contains("abc") { 
        // do
    }
    

    或者可以使用正则表达式。

    Match match = Regex.Match(line, "REGEXPRESSION_HERE");
    
        3
  •  1
  •   Elisha    15 年前

    要打印所有实例,可以使用以下代码:

    int index = 0;
    
    while ( (index = s.IndexOf("abc", index)) != -1 )
    {
       Console.WriteLine(s.Substring(index + 3, 2));
    }
    

    此代码假定字符串实例之后始终有两个字符。

        4
  •  0
  •   Javier    15 年前

    我认为这是一个更清楚的例子:

        // Find the full path of our document
        System.IO.FileInfo ExecutableFileInfo = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);            
        string path = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "MyTextFile.txt");
    
        // Read the content of the file
        string content = String.Empty;
        using (StreamReader reader = new StreamReader(path))
        {
            content = reader.ReadToEnd();
        }
    
        // Find the pattern "abc"
        int index = -1; //First char index in the file is 0
        index = content.IndexOf("abc");
    
        // Outputs the next two caracters
        // [!] We need to validate if we are at the end of the text
        if ((index >= 0) && (index < content.Length - 4))
        {
            Console.WriteLine(content.Substring(index + 3, 2));
        }
    

    注意 这只适用于第一次巧合。我不知道你是否想展示所有的巧合。