Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing strings in lists C#

Tags:

string

c#

foreach

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

like image 460
Ilan Avatar asked Dec 06 '22 04:12

Ilan


2 Answers

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

like image 187
Kamil Budziewski Avatar answered Jan 03 '23 15:01

Kamil Budziewski


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);
like image 21
Sergey Berezovskiy Avatar answered Jan 03 '23 13:01

Sergey Berezovskiy