如何检查一个字符串在文件中是否唯一,以及它是否被写入另一个文件

本文关键字:是否 文件 另一个 唯一 检查 一个 字符串 何检查 | 更新日期: 2023-09-27 18:15:43

我有两个文件F1.txt和F2.txt。F1.txt包含一些内容,如

U1,U2
U1,U5
U3,U4
U2,U1
U3,U4

本质上U1 U2和U2 U1的意思是一样的。现在我要把不同的内容写入文件f2。txt也就是说写入f2。txt后应该包含

U1,U2
U1,U5
U3,U4

我试了下面的方法,但没有成功。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringInFileTechchef
{
    class Program
    {
        static void Main(string[] args)
        {
            string line = "";
            using (StreamReader sr = new StreamReader(@"C:'Users'Chiranjib'Desktop'F1.txt"))
            {
                while((line=sr.ReadLine()) !=null)
                {
                    if (!File.ReadAllText(@"C:'Users'Chiranjib'Desktop'F2.txt").Contains(line))
                    {
                        //char[] array = line.ToCharArray();
                        //Array.Reverse(array);
                        //string temp = new string(array);
                        string temp1 = line.Substring(0, 2);
                        string temp2 = line.Substring(3, 2);
                        if (!File.ReadAllText(@"C:'Users'Chiranjib'Desktop'F2.txt").Contains(temp2 + "," + temp1))
                        {
                            using (StreamWriter sw = new StreamWriter(@"C:'Users'Chiranjib'Desktop'F2.txt"))
                            {
                                sw.WriteLine(line);
                                Console.WriteLine(line);
                            }
                        }
                    }
                }
            }
            Console.ReadKey();
        }
    }
}

我错过了什么?如何实现场景

如何检查一个字符串在文件中是否唯一,以及它是否被写入另一个文件

我是这样做的:

取每一行并将其拆分为string[]

string[]排序

string[]接回string

取不同的strings

var distinct = File.ReadLines("TextFile2.txt")
    .Select(l => String.Join(",", l.Split(',').OrderBy(i => i)))
    .Distinct();
File.WriteAllLines("F2.txt", distinct);

另一个方法:

HashSet<string> uniqueLines = new HashSet<string>();
foreach(string line in File.ReadLines("F1.txt"))
{
    if (uniqueLines.Contains(line))
        continue;
    string[] tokens = line.Split(',');
    string reversedLine = string.Join(",", tokens.Reverse());
    if (uniqueLines.Contains(reversedLine))
        continue;
    uniqueLines.Add(line);
}
File.WriteAllLines("F2.txt", uniqueLines);

这对我很有效。基本上假设有两个字符串总是用逗号分开,我只是用HashSet把它们过滤掉。可能是多余的,但对小文件有效。

#region
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
#endregion
namespace StringInFileTechchef
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            HashSet<WordCombo> existingWordCombos = GetWordCombos(File.ReadAllLines(@"C:'Users'Chiranjib'Desktop'F2.txt"));
            HashSet<WordCombo> newWordCombos = GetWordCombos(File.ReadAllLines(@"C:'Users'Ganesh'Chiranjib'F1.txt"));
            foreach (WordCombo newWordCombo in newWordCombos)
            {
                existingWordCombos.Add(newWordCombo);
            }
            StringBuilder stringBuilder = new StringBuilder();
            foreach (WordCombo existingWordCombo in existingWordCombos)
            {
                stringBuilder.AppendFormat("{0},{1}{2}", existingWordCombo.SmallerWord, existingWordCombo.BiggerWord, Environment.NewLine);
            }
            File.WriteAllText(@"C:'Users'Ganesh'Desktop'F2.txt", stringBuilder.ToString());
        }
        private static HashSet<WordCombo> GetWordCombos(IEnumerable<string> lines)
        {
            HashSet<WordCombo> wordCombos = new HashSet<WordCombo>();
            foreach (string line in lines)
            {
                string[] splitWords = line.Split(new[] {','});
                wordCombos.Add(new WordCombo(splitWords[0], splitWords[1]));
            }
            return wordCombos;
        }
        private class WordCombo
        {
            public string BiggerWord { get; private set; }
            public string SmallerWord { get; private set; }
            public WordCombo(string part1, string part2)
            {
                if (0 < string.Compare(part1, part2, StringComparison.InvariantCultureIgnoreCase))
                {
                    BiggerWord = part1;
                    SmallerWord = part2;
                }
                else
                {
                    BiggerWord = part2;
                    SmallerWord = part1;
                }
            }
            protected bool Equals(WordCombo other)
            {
                return string.Equals(BiggerWord, other.BiggerWord, StringComparison.InvariantCultureIgnoreCase)
                       && string.Equals(SmallerWord, other.SmallerWord, StringComparison.InvariantCultureIgnoreCase);
            }
            public override bool Equals(object obj)
            {
                if (ReferenceEquals(null, obj)) return false;
                if (ReferenceEquals(this, obj)) return true;
                if (obj.GetType() != GetType()) return false;
                return Equals((WordCombo) obj);
            }
            public override int GetHashCode()
            {
                unchecked
                {
                    return ((BiggerWord != null ? BiggerWord.ToLowerInvariant().GetHashCode() : 0)*397) ^
                           (SmallerWord != null ? SmallerWord.ToLowerInvariant().GetHashCode() : 0);
                }
            }
        }
    }
}