Skip to main content
  1. About
  2. For Teams
Asked
Viewed 14k times
3

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;
}
2
  • 2
    You have to assign the result of Replace to a variable.
    Jan
    –  Jan
    2013-05-14 14:05:40 +00:00
    Commented May 14, 2013 at 14:05
  • 3
    I think Replace have a return value. Did you try excel = excel.Replace(' ','_'); ?
    Pierre-Luc Pineault
    –  Pierre-Luc Pineault
    2013-05-14 14:05:46 +00:00
    Commented May 14, 2013 at 14:05

4 Answers 4

19

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.

Sign up to request clarification or add additional context in comments.

2 Comments

and others were too slow =D
Downvoter please leave a comment - how can I improve this answer?
4

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

So you should do :

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

Comments

4

You need to set excel to the replaced version.

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

Comments

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

Replace does not change the string on place.

1 Comment

Thank you! that worked, missed that detail... will accept soon!

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.