【问题标题】:Replacing strings in lists C#替换列表中的字符串 C#
【发布时间】:2013-10-30 07:19:17
【问题描述】:

我一直在编写一个程序来存储学生姓名和年龄(名字、姓氏、年龄在 .txt 文件中)。我现在正在制作“删除学生”部分,当我希望用户选择要删除的名称(通过切断文件名的 .txt 扩展名来打印)时,它不会替换“.txt”部分一无所有。
代码是:

    string inputSel; // Selection string for delete
    Console.WriteLine(" -- Deleting Grade {0} -- ", grade);
    Console.WriteLine("- Enter a student name to delete: ");
    foreach (string file in fileNames)
    {
        file.Replace(".txt", "");
        studentNames.Add(file);
        Console.WriteLine(file); // debug
    }
    foreach (string name in studentNames)
    {
        Console.Write("{0}\t", name);
    }
    Console.WriteLine();
    Console.Write("> ");
    inputSel = Console.ReadLine();

其中 fileNames 是 List<string>,它是此代码所在方法的参数。studentNames 也是 List<string>,它存储名称(不带 .txt 的文件名),但它仍然打印名称出于某种原因使用 .txt。
长话短说,它不会将".txt" 替换为""

【问题讨论】:

    标签: c# string foreach


    【解决方案1】:

    这是因为 String.Replace 返回值,不修改见here

    file = file.Replace(".txt", "");
    

    我建议使用

    file = Path.GetFileNameWithoutExtension(file);
    

    Path.GetFileNameWithoutExtension 将适用于所有扩展,它看起来更干净,并说明那里做了什么:)

    【讨论】:

      【解决方案2】:

      String.Replace 方法创建新字符串。它不会修改您传递的字符串。您应该将替换结果分配给您的字符串:

      file = file.Replace(".txt", "");
      

      另外我建议你使用Path.GetFileNameWithoutExtension 来获取不带扩展名的文件名

      file = Path.GetFileNameWithoutExtension(file);
      

      【讨论】:

        【解决方案3】:

        您在替换“.txt”后省略了设置文件值 试试这个:

        ...
        foreach (string file in fileNames)
        {
            file = file.Replace(".txt", "");
            studentNames.Add(file);
            Console.WriteLine(file); // debug
        }
        ...
        

        【讨论】:

          【解决方案4】:
          string.Replace();
          

          不修改返回副本的字符串。另一个问题是foreach iterators are readonly 所以你需要这样的东西。

          fileNames = fileNames.Select
                      (Path.GetFileNameWithoutExtension);
          

          希望这会有所帮助!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-05-22
            • 1970-01-01
            • 2012-11-26
            • 2013-05-01
            • 2017-06-22
            • 1970-01-01
            • 2013-11-15
            • 2019-01-30
            相关资源
            最近更新 更多