如何检查字符串在文件中是否唯一以及是否在C#中写入另一个文件?

时间:2015-10-03 05:53:38

标签: c# file

我有两个文件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();
        }
    }
}

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

3 个答案:

答案 0 :(得分:2)

我将如何做到这一点:

取每一行并将其拆分为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);

答案 1 :(得分:1)

另一种方法:

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

答案 2 :(得分:1)

这对我有用。基本上假设有两个字符串总是以逗号分隔,我只是使用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);
                }
            }
        }
    }
}