String not removed

  • Thread starter Thread starter Nadav
  • Start date Start date
N

Nadav

hi,
I have a string, I use the Remove method and the string stays the same.

ublic static bool CreatePrepareFile(string path)

{

Console.WriteLine(path);

int ind = path.LastIndexOf('\\');

Console.WriteLine("index is : {0}", ind);

path.Remove(ind);



This code is to take out the path out of a full filename. The index is
correct, I checked, but the string isn't removed as should!

why ?
Thanks.
 
Nadav said:
hi,
I have a string, I use the Remove method and the string stays the same.

ublic static bool CreatePrepareFile(string path)

{

Console.WriteLine(path);

int ind = path.LastIndexOf('\\');

Console.WriteLine("index is : {0}", ind);

path.Remove(ind);



This code is to take out the path out of a full filename. The index is
correct, I checked, but the string isn't removed as should!

Because the Remove method does not alter the string. Instead if
returns a new string without the part to be removed. To use the Remove
method properly, you would need code like this:

string s1 = "ABCDEF";
s1 = s1.Remove(....);

If you need to get a filename without the path, then just use the
Path.GetFileName() method from the System.IO namespace.

Chris
 
Nadav said:
hi,
I have a string, I use the Remove method and the string stays the same.

ublic static bool CreatePrepareFile(string path)

{

Console.WriteLine(path);

int ind = path.LastIndexOf('\\');

Console.WriteLine("index is : {0}", ind);

path.Remove(ind);



This code is to take out the path out of a full filename. The index is
correct, I checked, but the string isn't removed as should!

why ?
Thanks.

Strings are immutable, so all methods return a new string with the
desired modification. So if you write:

path = path.Remove(ind);

it should have the desired effect.

HTH,
Andy
 
Back
Top