繁体   English   中英

在txt文件中搜索字符串

[英]Searching strings in txt file

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

123|this data is variable|
456|this data is variable|
789|so is this|
etc..

我希望在C#中编写一个程序,它将读取.txt文件,如果我指定了我想要的字符串的ID,则只显示174个字符串中的一个。 这是因为在文件中我的所有数据都是可变的,因此只能使用ID来拉取字符串。 因此,不要仅仅结束我只得到一行的例子。

例如,只是

123|this data is variable| 

我似乎能够编写一个程序,它只会从.txt文件中提取ID,而不是整个字符串或一个程序,它会读取整个文件并显示它。 但我还没想到,这正是我所需要的。 救命!

那么我从txt文件中获取的实际字符串没有'|' 他们只是在这个例子中。 真实字符串的示例是:0111111(0010101),其中括号中的数据是可变的。 括号也不存在于真正的字符串中。

namespace String_reader {class Program {static void Main(string [] args){String 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();


    }
}

}

使用正则表达式。 Regex.Match("|"+inputString+"|",@"\\|[ ]*\\d+\\|(.+?)\\|").Groups[1].Value

哦,我差点忘了; 你需要用d+代替你想要的实际索引。 现在,那只会让你第一个。

“|” 在输入字符串之前和之后确保索引和值都包含在|中 对于所有元素,包括第一个和最后一个。 有没有它的方法做一个正则表达式,但恕我直言他们只是让你的正则表达式更复杂,更不易阅读。

假设你有pathid

Console.WriteLine(File.ReadAllLines(path).Where(l => l.StartsWith(id + "|")).FirstOrDefault());

使用ReadLines获取行的字符串数组,然后在|上进行字符串拆分

您可以使用Regex.Split方法

FileInfo info = new FileInfo("filename.txt");
String[] lines = info.OpenText().ReadToEnd().Split(' ');

foreach(String line in lines)
{
    int id = Convert.ToInt32(line.Split('|')[0]);
    string text = Convert.ToInt32(line.Split('|')[1]);
}
  • 将数据读入字符串
  • 拆分“|”字符串
  • 阅读2乘2项:key:value,key:value,...
  • 将它们添加到字典中

现在,您可以使用字典[key]轻松找到您的字符串。

    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);

请注意,使用.NET 4.0,您不需要ReadLines函数,因为有ReadLines

你现在可以像任何字典一样使用它:

 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]);

希望这就是你要找的东西。

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

StreamReader sr = new StreamReader(filename);
string text = sr.ReadToEnd();
string[] data = text.Split('|');

然后将某些数据元素转换为数字和字符串,即int [] ID和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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM