gpt4 book ai didi

c# - 使用 Replace() 从开头删除引号会将它们全部删除

转载 作者:太空宇宙 更新时间:2023-11-03 23:05:04 24 4
gpt4 key购买 nike

我正在尝试从引号中过滤 csv 文件。这一行奇怪地删除了该行中的所有引号:

之前:"NewClient"Name"

foo = foo.Replace(foo.Substring(0, 1), "");

之后:NewClientName

为什么会这样? Replace() 方法不应该只删除第一次出现吗?

最佳答案

通常在处理 CSV 时我们加倍引号:

a                 -> "a"
a"b -> "a""b"
NewClient"Name -> "NewClient""Name"

要截断这样一个引用,即

"NewClient""Name" -> NewClient"Name

"NewClient"Name" 是一个语法错误时,您可以尝试

private static string CutQuotation(string value) {
if (string.IsNullOrEmpty(value))
return value;
else if (!value.Contains('"'))
return value;

if (value.Length == 1)
throw new FormatException("Incorrect quotation format: string can't be of length 1.");
else if (value[0] != '"')
throw new FormatException("Incorrect quotation format: string must start with \".");
else if (value[value.Length - 1] != '"')
throw new FormatException("Incorrect quotation format: string must end with \".");

StringBuilder builder = new StringBuilder(value.Length);

for (int i = 1; i < value.Length - 1; ++i)
if (value[i] == '"')
if (i == value.Length - 2)
throw new FormatException("Incorrect quotation format. Dangling \".");
else if (value[++i] == '"')
builder.Append(value[i]);
else
throw new FormatException("Incorrect quotation format. Dangling \".");
else
builder.Append(value[i]);

return builder.ToString();
}

如您所见,它不仅仅是单个 Replace() 例程。

测试:

 // abc - no quotation
Console.WriteLine(CutQuotation("abc"));
// abc - simple quotation cut
Console.WriteLine(CutQuotation("\"abc\""));
// "abc" - double quotation
Console.WriteLine(CutQuotation("\"\"abc\"\""));
// a"bc - quotation in the middle
Console.WriteLine(CutQuotation("\"a\"\"bc\""));

关于c# - 使用 Replace() 从开头删除引号会将它们全部删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41586455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com