【问题标题】:Removing Special Character from console to load a txt file从控制台删除特殊字符以加载 txt 文件
【发布时间】:2012-01-17 18:23:26
【问题描述】:

所以我的上一个问题不清楚,所以这是我的第二次尝试。

当我将我的 txt 文件拖放到控制台中时,我会得到这样的路径:

"C:\Dokumente und Einstellungen\Bektas\Desktop\test\text1.txt"

如何自动删除" 字符?

在将路径保存到字符串之前,我必须手动删除它...

这是我的代码:

    static void Main(string[] args)
    {
        String pfad;
        String pfad2;
        String speichern = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\ausgabe.txt";

        try
        {
            Console.WriteLine("Pfad eingeben: ");
            pfad = Console.ReadLine();

            Console.WriteLine("Pfad eingeben: ");
            pfad2 = Console.ReadLine();
            // Input
            List<String> data = File.ReadAllLines(pfad)
                .Concat(File.ReadAllLines(pfad2))
                .Distinct().ToList();

            // Processing
            data.Sort();

            // Output
            Console.WriteLine("Duplikate entfernt & sortiert:");
            data.ForEach(Console.WriteLine);
            File.WriteAllLines(speichern, data.ToArray());

        }
        catch (Exception e)
        {
            Console.WriteLine("Die Anwendung schlug fehl: {0}\t" + e.ToString());
        }

        Console.ReadKey();

    }
}

【问题讨论】:

  • 您能具体说明您的问题吗?你在哪里删除字符?

标签: c# console special-characters


【解决方案1】:

您可以通过执行以下操作自动删除 " 字符:

Console.WriteLine("Pfad eingeben: ");
pfad = Console.ReadLine();
if (pfad.StartsWith("\"") && pfad.EndsWith("\"")) {
    pfad = pfad.Substring(1, pfad.Length - 2);
}

另外,由于您使用pfadpfad2 执行此操作两次,您应该将此代码提取到函数中以减少代码重复:

private static string RemoveQuotes(string input) {
    if (input.StartsWith("\"") && input.EndsWith("\"")) {
        return input.Substring(1, input.Length - 2);
    } else {
        return input;
    }
}

public static void Main(string[] args) {

  // ...

  Console.WriteLine("Pfad eingeben: ");
  pfad = RemoveQuotes(Console.ReadLine());

  Console.WriteLine("Pfad eingeben: ");
  pfad2 = RemoveQuotes(Console.ReadLine());      

  // ...

}

【讨论】:

    【解决方案2】:

    pfad = pfad.Replace("\"", ""); 将所有 " 替换为空。

    【讨论】:

      【解决方案3】:

      如果您的“特殊字符串”比一个字符长,请执行以下操作:

      string replacedString = Regex.Replace(originalString, specialString);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-07
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 2016-02-04
        • 2016-10-17
        相关资源
        最近更新 更多