【问题标题】:replacing the beginning and end but not the same chars within a string替换字符串中的开头和结尾但不相同的字符
【发布时间】:2012-12-03 14:56:04
【问题描述】:
lines = "some stuff\"some other \"stuff\"\"";
lines = lines.Replace("\"", "\"");
lines = lines.Replace("\"", "\"");

在当前的上下文和最简单的形式中,这两个动作似乎毫无意义,但是当我将其放入代码中时,它并非毫无意义,并且除了用自身替换自身之外,还有其他目的。

好的,所以我有包含 4 个转义引号的字符串行,我希望将第一个引号替换为引号,将结束引号替换为引号我将如何在不替换任何内部引号的情况下完成此操作?

【问题讨论】:

  • 您想用引号替换引号?你能发布结果应该是什么样子吗:)

标签: c# regex replace contains


【解决方案1】:

使用 IndexOf 和 LastIndexOf 查找第一个和最后一个引号。然后使用 Substring 替换引号:

lines = "some stuff\"some other \"stuff\"\"";
firstQuote = lines.IndexOf("\"");
lastQuote = lines.LastIndexOf("\"");
lines = lines.Substring(0, firstQuote) + "\"" + lines.Substring(firstQuote + 1, lastQuote) + "\"" + lines.Substring(lastQuote + 1, lines.Length);

【讨论】:

  • 只是想知道行中的最后一个引号是否应该。Substring(firstQuote + 1, lastQuote) + ">";是最后一个 - 1? (第二行.substring())因为当前由于长度超出范围而中断ideone.com/CCxwMB
  • 呵呵忽略我对 - 1 的评论,因为 endQuote = 29 并且 lines = 30 但参数长度仍然超出范围?
  • 您使用的是 Substr,但我的示例使用的是 Substring。要使其与 Substr 一起使用,您需要从第二个参数中减去第一个参数。例如,lines.Substring(firstQuote + 1, lastQuote) 变为lines.Substr(firstQuote + 1, lastQuote - (firstQuote + 1))
  • 我完全复制了您的示例,只是将所有出现的“行”更改为“输入”,我在哪里使用 Substr 而不是 Substring?
  • 显然您的语言名称颠倒了。通常,Subtring 有参数(开始,结束),而 Substr 有参数(开始,长度)。所以只需减去我之前评论中的参数,它应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2012-01-18
  • 2013-06-13
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
相关资源
最近更新 更多