Strip double quotes from a string in .NET

后端 未结 12 2029
抹茶落季
抹茶落季 2020-12-24 04:16

I\'m trying to match on some inconsistently formatted HTML and need to strip out some double quotes.

Current:




        
相关标签:
12条回答
  • 2020-12-24 04:47

    If you only want to strip the quotes from the ends of the string (not the middle), and there is a chance that there can be spaces at either end of the string (i.e. parsing a CSV format file where there is a space after the commas), then you need to call the Trim function twice...for example:

    string myStr = " \"sometext\"";     //(notice the leading space)
    myStr = myStr.Trim('"');            //(would leave the first quote: "sometext)
    myStr = myStr.Trim().Trim('"');     //(would get what you want: sometext)
    
    0 讨论(0)
  • 2020-12-24 04:58

    I think your first line would actually work but I think you need four quotation marks for a string containing a single one (in VB at least):

    s = s.Replace("""", "")
    

    for C# you'd have to escape the quotation mark using a backslash:

    s = s.Replace("\"", "");
    
    0 讨论(0)
  • 2020-12-24 05:03

    I didn't see my thoughts repeated already, so I will suggest that you look at string.Trim in the Microsoft documentation for C# you can add a character to be trimmed instead of simply trimming empty spaces:

    string withQuotes = "\"hellow\"";
    string withOutQotes = withQuotes.Trim('"');
    

    should result in withOutQuotes being "hello" instead of ""hello""

    0 讨论(0)
  • 2020-12-24 05:03
    s = s.Replace("\"", "");
    

    You need to use the \ to escape the double quote character in a string.

    0 讨论(0)
  • 2020-12-24 05:03

    if you would like to remove a single character i guess it's easier to simply read the arrays and skip that char and return the array. I use it when custom parsing vcard's json. as it's bad json with "quoted" text identifiers.

    Add the below method to a class containing your extension methods.

      public static string Remove(this string text, char character)
      {
          var sb = new StringBuilder();
          foreach (char c in text)
          {
             if (c != character)
                 sb.Append(c);
          }
          return sb.ToString();
      }
    

    you can then use this extension method:

    var text= myString.Remove('"');
    
    0 讨论(0)
  • 2020-12-24 05:04
    s = s.Replace("\"",string.Empty);
    
    0 讨论(0)
提交回复
热议问题