Replace string spaces with an underscore

12,485

Solution 1

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.

Solution 2

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

So you should do :

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

Solution 3

You need to set excel to the replaced version.

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

Solution 4

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

Replace does not change the string on place.

Share:
12,485
Ignacio Nimo
Author by

Ignacio Nimo

Ingeniero de Sistemas / Computer Science

Updated on June 29, 2022

Comments

  • Ignacio Nimo
    Ignacio Nimo almost 2 years

    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;
    }
    
  • Ignacio Nimo
    Ignacio Nimo almost 11 years
    Thank you! that worked, missed that detail... will accept soon!
  • Sinatr
    Sinatr almost 11 years
    and others were too slow =D
  • DGibbs
    DGibbs over 10 years
    Downvoter please leave a comment - how can I improve this answer?