Ignacio Nimo
Ignacio Nimo

Reputation: 65

Replace string spaces with an underscore

I need to replace some spaces with an underscore (i.e. "PM HD PSP" > "PM_HD_PSP")

Here's what I've tried so far:

private string NombreExcel3(string excel)
{
    MessageBox.Show(excel);

    excel.Replace(' ','_');

    MessageBox.Show(excel);
    return excel;
}

Upvotes: 3

Views: 13685

Answers (4)

DGibbs
DGibbs

Reputation: 14618

Strings are immutable, you need to do:

excel = excel.Replace(' ','_');

String.Replace() wont alter the original string, it will instead return a new altered string.

String.Replace(): Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.

Upvotes: 19

Romain Vergnory
Romain Vergnory

Reputation: 1598

excel = excel.Replace(' ','_');

Replace does not change the string on place.

Upvotes: 2

Lily
Lily

Reputation: 316

You need to set excel to the replaced version.

excel = excel.Replace(' ','_');

Upvotes: 4

Marshall777
Marshall777

Reputation: 1204

string.Replace(...) returns a new string object without modifying the original one

So you should do :

excel = excel.Replace(' ','_');

Upvotes: 4

Related Questions