views:

181

answers:

4
public static class StringHelper 
{
  public static string HyphenAndSpaceReplacer(this string s) 
  {
 string newString = s;
 newString.Replace(char.Parse(" ", "_"));
 newString.Replace(char.Parse("-", "_"));

 return newString;
  }
}

Error:

  1. No overload for method 'Parse' takes '2' arguments
  2. No overload for method 'Replace' takes '1' arguments

I'm trying to replace spaces and hyphens with underscores in file names with the piece of code above but I keep getting those errors. Please tell me what I'm missing or if it is totally wrong.

A: 

Try the following

newString = newString.Replace(' ', '_');
newString = newString.Replace('-', '_');

The Char.Parse method is not necessary here. To use a char simply use the ' syntax instead of the ".

Also, strings in C# (CLR) are immutable so to see the result of the replacement you need to assign it back to newString.

JaredPar
+2  A: 
public static class StringHelper 
{
  public static string HyphenAndSpaceReplacer(this string s) 
  {
        string newString = s;
        newString = newString.Replace(" ", "_");
        newString = newString.Replace("-", "_");

        return newString;
  }
}

Remember, strings are immutable, so you need to assign the result of Replace back to a string variable. That's not why you were getting the errors though, but just something to keep in mind.

BFree
You can also chain together the .Replace() calls if you like: newString = newString.Replace(" ", "_").Replace("-", "_");
scwagner
this worked thanx alot!
jason
A: 

Strings are immutable. You only need to:

public static class StringHelper 
{
  public static string HyphenAndSpaceReplacer(this string s) 
  {
        return s.Replace(' ', '_').Replace('-', '_');
  }
}
bruno conde
A: 

To improve upon BFree's implementation

public static class StringHelper 
{
 public static string HyphenAndSpaceReplacer(this string s) 
   {
       //Only process if certain criteria are met
      if(s != null || s != string.Empty ||s.contains(' ') || s.contains('-')
      {
         string newString = s;
         newString = newString.Replace(" ", "_");
         newString = newString.Replace("-", "_");
         return newString;
      }
    //else just return the string
    return s;
    }
}
Woot4Moo