Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在txt文件中搜索字符串_C# - Fatal编程技术网

C# 在txt文件中搜索字符串

C# 在txt文件中搜索字符串,c#,C#,我有一个包含174个不同字符串的.txt文件。每个字符串都有一个唯一的标识符。 例如: 123|this data is variable| 456|this data is variable| 789|so is this| etc.. 我希望用C#编写一个程序,如果指定所需字符串的ID,它将读取.txt文件并仅显示174个字符串中的一个。这是因为在我拥有的文件中,所有数据都是可变的,因此只能使用ID来提取字符串。因此,我没有以这个例子结束,我只得到了一行 刚刚 123|this data

我有一个包含174个不同字符串的.txt文件。每个字符串都有一个唯一的标识符。 例如:

123|this data is variable|
456|this data is variable|
789|so is this|
etc..
我希望用C#编写一个程序,如果指定所需字符串的ID,它将读取.txt文件并仅显示174个字符串中的一个。这是因为在我拥有的文件中,所有数据都是可变的,因此只能使用ID来提取字符串。因此,我没有以这个例子结束,我只得到了一行

刚刚

123|this data is variable| 
我似乎能够编写一个只从.txt文件中提取ID的程序,而不是整个字符串,或者一个只读取整个文件并显示它的程序。但我还没有完全做到我所需要的。救命啊


我从txt文件中得到的实际字符串没有“|”,它们就在示例中。实际字符串的一个示例是:011111(0010101),其中括号中的数据是可变的。括号在实际字符串中也不存在

名称空间字符串读取器 { 班级计划 { 静态void Main(字符串[]参数) { 字符串filepath=@“C:\my file name here”; 弦线

        if(File.Exists(filepath))

        {
            StreamReader file = null;
            try
            {
                file = new StreamReader(filepath);
                while ((line = file.ReadLine()) !=null)
                {
                    string regMatch = "ID number here"; //this is where it all falls apart.
                    Regex.IsMatch (line, regMatch);

                    Console.WriteLine (line);// When program is run it just displays the whole .txt file
                }
            }
        }
        finally{
            if (file !=null)
                file.Close();
        }
    }
    Console.ReadLine();


    }
}

}

使用ReadLines获取一个字符串数组,然后在|

上拆分字符串。您可以使用拆分方法将整个文本拆分为由“|”分隔的部分。然后所有偶数元素将对应于数字奇数元素-字符串

StreamReader sr = new StreamReader(filename);
string text = sr.ReadToEnd();
string[] data = text.Split('|');
然后将某些数据元素转换为数字和字符串,即int[]IDs和string[]Strs。使用idx=Array.FindIndex(IDs,ID.Equals)查找给定ID的索引,相应的字符串将是Strs[idx]

List <int> IDs;
List <string> Strs;
for (int i = 0; i < data.Length - 1; i += 2)
{
    IDs.Add(int.Parse(data[i]));
    Strs.Add(data[i + 1]);
}
idx = Array.FindIndex(IDs, ID.Equals); // we get ID from input
answer = Strs[idx];
列表id;
列出可疑交易报告;
对于(int i=0;i
您可以使用方法

假设您有
路径
id

Console.WriteLine(File.ReadAllLines(path).Where(l => l.StartsWith(id + "|")).FirstOrDefault());
  • 将数据读入字符串
  • 在“|”上拆分字符串
  • 按2:key:value,key:value
  • 将它们添加到字典中

现在你可以很容易地用字典[key]找到你的字符串。

使用正则表达式。类似于
Regex.Match(“|”+inputString+“|”,@“\\\\[]*\d+\\\\\(.+?)\\\\\\”。组[1]。值

哦,我差点忘了;你需要用
d+
替换你想要的实际索引。现在,这就得到了第一个索引

输入字符串前后的“|”确保所有元素(包括第一个和最后一个)的索引和值都包含在一个|中。在没有它的情况下,可以使用正则表达式,但它们只会使正则表达式更复杂,可读性更低

    private static IEnumerable<string> ReadLines(string fspec)
    {
        using (var reader = new StreamReader(new FileStream(fspec, FileMode.Open, FileAccess.Read, FileShare.Read)))
        {
            while (!reader.EndOfStream)
                yield return reader.ReadLine();
        }
    }

    var dict = ReadLines("input.txt")
        .Select(s =>
                    {
                        var split = s.Split("|".ToArray(), 2);
                        return new {Id = Int32.Parse(split[0]), Text = split[1]};
                    })
        .ToDictionary(kv => kv.Id, kv => kv.Text);

此处无错误处理,请添加您自己的

首先将孔文件加载到字符串中。
然后试试这个:

string s = "123|this data is variable| 456|this data is also variable| 789|so is this|";
int index = s.IndexOf("123", 0);
string temp = s.Substring(index,s.Length-index);
string[] splitStr = temp.Split('|');
Console.WriteLine(splitStr[1]);

希望这就是您所寻找的。

向我们展示您已经拥有的代码。您好。请发布您迄今为止尝试过的代码/方法的示例。您的代码很好。您所需要的只是为正则表达式修复模式。请参阅Flynn post。此外,您可以使用拆分获取所有数据,然后将其存储在字典类型struc中true,这样您就不必不断地从file.static void Main(string[]args){string filepath=@“C:\my file name here”;字符串行;如果(file.Exists(filepath)){StreamReader file=null;请重试{file=newstreamreader(filepath);while((line=file.ReadLine())!=null){我从txt文件中得到的实际字符串没有“|”,它们只是在示例中。实际字符串的示例是:011111(0010101)括号中的数据是可变的。括号不存在于实际字符串中。当然,使用regex
@“011111([01]{7})”
可以在本例中找到该值;当然,如果变量数据恰好包含与有效索引相同的值,则会出现问题。
 Console.WriteLine(dict[12]);
 Console.WriteLine(dict[999]);
string s = "123|this data is variable| 456|this data is also variable| 789|so is this|";
int index = s.IndexOf("123", 0);
string temp = s.Substring(index,s.Length-index);
string[] splitStr = temp.Split('|');
Console.WriteLine(splitStr[1]);