Ilan
Ilan

Reputation: 513

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 "".

Upvotes: 4

Views: 259

Answers (4)

Ryan T. Grimm
Ryan T. Grimm

Reputation: 1325

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!

Upvotes: 1

tdelepine
tdelepine

Reputation: 2016

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
}
...

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

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

Upvotes: 3

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

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

Upvotes: 8

Related Questions