简体   繁体   中英

Replacing strings in lists C#

I've been coding a program that stores student names and age (First name, last name, age in a .txt file). I am now making the "delete student" part, and when I want the user to select what name to delete (which is printed by cutting off the .txt extension of the filenames), it doesn't replace the ".txt" part with nothing.
The code is:

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

Where fileNames is a List<string> , it is a parameter for the method this code is in. studentNames is also a List<string> , where it stores the names (file name without .txt), but it still prints the name with .txt for some reason.
Long story short, it doesn't replace ".txt" with "" .

It's because String.Replace returns value, not modifies see here

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

I suggest using

file = Path.GetFileNameWithoutExtension(file);

Path.GetFileNameWithoutExtension will work with all extensions and it looks cleaner and says what is done there :)

String.Replace method creates new string. It does not modifies string which you are passing. You should assign result of replacement to your string:

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

Also I suggest you to use Path.GetFileNameWithoutExtension to get file name without extension

file = Path.GetFileNameWithoutExtension(file);

You have omitted to set file value after replace ".txt" Try this :

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

Does not modify the string it returns a copy. The other problem is that foreach iterators are readonly so you need to something like this.

fileNames = fileNames.Select
            (Path.GetFileNameWithoutExtension);

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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