在C#中取消引用字符串

39

我有一个类似INI文件格式的数据文件,需要被一些C代码和一些C#代码读取。C代码期望字符串值被引号包围。C#等效的代码正在使用某些底层类或其他我无法控制的东西,但基本上它将引号作为输出字符串的一部分。也就是说,数据文件的内容如下:

MY_VAL="Hello World!"

给了我

"Hello World!"

在我的C#字符串中,当我真正需要它包含时

Hello World!

如何根据条件(即首尾字符为引号)去除引号并获取所需的字符串内容。


3
多年以后,我仍然在这个简单问题上获得投票和徽章(因为有很多浏览量)。太好了!我喜欢这个网站。 - AlastairG
10个回答

72

在你的字符串上使用Trim方法,并将参数设置为双引号字符:

.Trim('"')

4
请注意有一个陷阱:根据定义,Trim函数“删除一组字符的所有前导和尾随出现”,因此您可能会意外删除过多的引号。例如,当MY_VAL="c:\Users;\"c:\Program Files\""时,Trim()将从字符串末尾删除两个引号字符。 - Paweł Bulwan

9

我通常使用String.Trim()来实现这个目的:

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

8

我的实现会检查引号是否在两侧

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

1

作为一个有点固执的人,(这是我;不要评论你自己),你可能想考虑

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

这样可以去除引号外的任何空格,然后去除引号,最后去除所包含字符串的任何边界空格。

  • 如果要保留包含的边界空格,则省略最后一个 .Trim(' ')。
  • 如果有嵌入的空格和/或引号,它们将被保留。很可能这是需要的,不应该删除。
  • 对于类似换页符和/或制表符的东西,进行一些研究以了解无参数 Trim() 的作用。它可能只需要使用一个或另一个 Trim()。

更好的做法是使用以下代码: .Trim(' ', '"') - jakobbg

1

只需获取返回的字符串并执行 Trim('"'); 即可。


0
如果你知道字符串总是以双引号开头和结尾,那么这将是最快的方法。
s = s.Substring(1, s.Length - 2);

问题明确表示“有条件地(在第一个和最后一个字符都是“)”的情况下),这意味着开头和结尾不一定总是有引号。 - AlastairG

0
这是我的扩展方法解决方案:
public static class StringExtensions
{
  public static string UnquoteString(this string inputString) => inputString.TrimStart('"').TrimEnd('"');
}

这只是在开头和结尾进行修剪...


0
我建议使用replace()方法。
string str = "\"HelloWorld\"";
string result = str.replace("\"", string.Empty);

1
如果我的理解是正确的,这也将从字符串中间删除引号。它也不会受到第一个和最后一个字符是否为引号的条件限制。 - AlastairG

0
使用字符串替换函数或修剪函数。 如果您只想删除第一个和最后一个引号,请使用子字符串函数。
string myworld = "\"Hello World!\"";
string start = myworld.Substring(1, (myworld.Length - 2));

-1
你正在尝试做的通常被称为“剥离”或“解引用”。通常情况下,当一个值被引用时,这不仅意味着它被引号字符(比如在这个例子中是双引号)包围,而且还可能包含一些特殊字符来包括在被引用的文本中的引号字符本身。
简而言之,你应该考虑使用类似以下内容的东西:
string s = @"""Hey ""Mikey""!";
s = s.Trim('"').Replace(@"""""", @"""");

或者在使用撇号时:

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

有时候,根本不需要引用值(即不包含空格),因此可能根本不需要引用。这就是在修剪之前检查引号字符的原因。

考虑创建一个帮助函数,以以下示例中的首选方式执行此操作。

    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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接