开发者

Unquote string in C#

I have a data file in INI file l开发者_运维技巧ike format that needs to be read by both some C code and some C# code. The C code expects string values to be surrounded in quotes. The C# equivalent code is using some underlying class or something I have no control over, but basically it includes the quotes as part of the output string. I.e. data file contents of

MY_VAL="Hello World!"

gives me

"Hello World!"

in my C# string, when I really need it to contain

Hello World!

How do I conditionally (on having first and last character being a ") remove the quotes and get the string contents that I want.


On your string use Trim with the " as char:

.Trim('"')


I usually call String.Trim() for that purpose:

string source = "\"Hello World!\"";
string unquoted = source.Trim('"');


My implementation сheck that quotes are from both sides

public string UnquoteString(string str)
{
    if (String.IsNullOrEmpty(str))
        return str;

    int length = str.Length;
    if (length > 1 && str[0] == '\"' && str[length - 1] == '\"')
        str = str.Substring(1, length - 2);

    return str;
}


Just take the returned string and do a Trim('"');


Being obsessive, here (that's me; no comment about you), you may want to consider

  .Trim(' ').Trim('"').Trim(' ')

so that any, bounding spaces outside of the quoted string are trimmed, then the quotation marks are stripped and, finally, any, bounding spaces for the contained string are removed.

  • If you want to retain contained, bounding white space, omit the final .Trim(' ').
  • Should there be embedded spaces and/or quotation marks, they will be preserved. Chances are, such are desired and should not be deleted.
  • Do some study as to what a no argument Trim() does to things like form feed and/or tabulation characters, bounding and embedded. It could be that one and/or the other Trim(' ') should be just Trim().


If you know there will always be " at the end and beginning, this would be the fastest way.

s = s.Substring(1, s.Length - 2);


Use string replace function or trim function. If you just want to remove first and last quotes use substring function.

string myworld = "\"Hello World!\"";
string start = myworld.Substring(1, (myworld.Length - 2));


I would suggest using the replace() method.

string str = "\"HelloWorld\"";
string result = str.replace("\"", string.Empty);


What you are trying to do is often called "stripping" or "unquoting". Usually, when the value is quoted that means not only that it is surrounded by quotation characters (like " in this case) but also that it may or may not contain special characters to include quotation character itself inside quoted text.

In short, you should consider using something like:

string s = @"""Hey ""Mikey""!";
s = s.Trim('"').Replace(@"""""", @"""");

Or when using apostrophe mark:

string s = @"'Hey ''Mikey''!";
s = s.Trim('\'').Replace("''", @"'");

Also, sometimes values that don't need quotation at all (i.e. contains no whitespace) may not need to be quoted anyway. That's the reason checking for quotation characters before trimming is reasonable.

Consider creating a helper function that will do this job in a preferable way as in the example below.

    public static string StripQuotes(string text, char quote, string unescape)a
    {
        string with = quote.ToString();
        if (quote != '\0')
        {
            // check if text contains quote character at all
            if (text.Length >= 2 && text.StartsWith(with) && text.EndsWith(with))
            {
                text = text.Trim(quote);
            }
        }
        if (!string.IsNullOrEmpty(unescape))
        {
            text = text.Replace(unescape, with);
        }
        return text;
    }
using System;

public class Program
{
    public static void Main()
    {
        string text = @"""Hello World!""";
        Console.WriteLine(text);

        // That will do the job
        // Output: Hello World!
        string strippedText = text.Trim('"');
        Console.WriteLine(strippedText);

        string escapedText = @"""My name is \""Bond\"".""";
        Console.WriteLine(escapedText);

        // That will *NOT* do the job to good
        // Output: My name is \"Bond\".
        string strippedEscapedText = escapedText.Trim('"');
        Console.WriteLine(strippedEscapedText);

        // Allow to use \" inside quoted text
        // Output: My name is "Bond".
        string strippedEscapedText2 = escapedText.Trim('"').Replace(@"\""", @"""");
        Console.WriteLine(strippedEscapedText2);

        // Create a function that will check texts for having or not
        // having citation marks and unescapes text if needed.
        string t1 = @"""My name is \""Bond\"".""";
        // Output: "My name is \"Bond\"."
        Console.WriteLine(t1);
        // Output: My name is "Bond".
        Console.WriteLine(StripQuotes(t1, '"', @"\"""));
        string t2 = @"""My name is """"Bond"""".""";
        // Output: "My name is ""Bond""."
        Console.WriteLine(t2);
        // Output: My name is "Bond".
        Console.WriteLine(StripQuotes(t2, '"', @""""""));
    }
}

https://dotnetfiddle.net/TMLWHO


Here's my solution as extension method:

public static class StringExtensions
{
  public static string UnquoteString(this string inputString) => inputString.TrimStart('"').TrimEnd('"');
}

It's just trimming at the start an the end...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜