【问题标题】:How to replace text within a string based on their indices如何根据索引替换字符串中的文本
【发布时间】:2014-12-20 00:26:35
【问题描述】:

我有一串来自数据库的文本。我还有一个来自数据库的链接列表,这些链接的起始索引和长度与我的字符串相对应。我想将文本中的链接附加为链接

<a href=...

var stringText = "Hello look at http://www.google.com and this hello.co.uk";

这将在数据库中

Link:http://www.google.com
Index:14
Length:21

Link:hello.co.uk
Index:45
Length:11

我最终想要

var stringText = "Hello look at <a href="http://www.google.com">http://www.google.com</a> and this <a href="hello.co.uk">hello.co.uk</a>";

字符串中可能有很多链接,所以我需要一种循环遍历这些链接并根据索引和长度进行替换的方法。我会根据链接(string.replace)循环并替换,但如果有两次相同的链接会导致问题

var stringText = "www.google.com www.google.com www.google.com";

www.google.com 将成为一个链接,第二次将使该链接内的链接...成为一个链接。

我显然可以找到第一个索引,但如果我在那个时候更改它,则索引不再有效。

有没有简单的方法可以做到这一点,还是我错过了什么?

【问题讨论】:

  • 我猜你真的希望 &lt;a href="http://hello.co.uk/"&gt; 访问该站点,而不是 &lt;a href="hello.co.uk"&gt;,后者从 http://example.net/somewhere/else 转到 http://example.net/somewhere/hello.co.uk
  • 对于这样的应用,我更喜欢标记而不是索引
  • 这不是简单地对替换的起始索引进行排序并确保首先替换索引最高的那些吗?
  • @JonHanna 你是对的,这是一个糟糕的例子,在现实中我有一个用于这些场景的“OriginalTextLink”字段和“LinkTextLink”字段。

标签: c# string


【解决方案1】:

您只需使用String.Remove 从源中删除主题,然后使用String.Insert 插入替换字符串。

正如@hogan 在 cmets 中建议的那样,您需要对替换列表进行排序并以相反的顺序(从最后一个到第一个)进行替换以使其正常工作。

如果您需要在单个字符串中执行多次替换,出于性能原因,我推荐StringBuilder

【讨论】:

  • 首先对列表进行排序并从“最后一个”替换开始。这样数字就保持有效。
  • 糟糕! @霍根。很好的一点,否则将无法正常工作。更新了我的答案。谢谢。
  • 谢谢,好主意。发挥了魅力
【解决方案2】:

我会使用正则表达式。

看看这个:Regular expression to find URLs within a string

这可能会有所帮助。

【讨论】:

  • 如果您不熟悉 RegEx,请查看 .NET 中的 URI
  • 这将替换所有出现的字符串,不是吗?这不是 OP 想要的。
  • 这已经完成了,这就是为什么我从最初使用正则表达式的表格中获得了 URL 的索引
  • 可以但是不会造成多次替换的问题,每个url都会替换一次。
  • 那么为什么不使用正则表达式来查找这些并替换为链接呢?另外,为什么不在将字符串与多个 url 连接之前进行替换,然后再添加链接字符串?
【解决方案3】:

这是没有RemoveInsert 或正则表达式的解决方案。只是添加。

string stringText = "Hello look at http://www.google.com and this hello.co.uk!";

var replacements = new [] {
    new { Link = "http://www.google.com", Index = 14, Length = 21 },
    new { Link = "hello.co.uk", Index = 45, Length = 11 } };

string result = "";
for (int i = 0; i <= replacements.Length; i++)
{
    int previousIndex = i == 0 ? 0 : replacements[i - 1].Index + replacements[i - 1].Length;
    int nextIndex = i < replacements.Length ? replacements[i].Index : replacements[i - 1].Index + replacements[i - 1].Length + 1;

    result += stringText.Substring(previousIndex, nextIndex - previousIndex);

    if (i < replacements.Length)
    {
        result += String.Format("<a href=\"{0}\">{1}</a>", replacements[i].Link,
            stringText.Substring(replacements[i].Index, replacements[i].Length));
    }
}

【讨论】:

    猜你喜欢
    • 2016-08-28
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2023-02-02
    相关资源
    最近更新 更多