开发者

No overload for method Error

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开发者_StackOverflow中文版 code above but I keep getting those errors. Please tell me what I'm missing or if it is totally wrong.


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.


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.


Strings are immutable. You only need to:

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


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜