![](/img/trans.png)
[英]How to replace a String twice with oldValues having same text within?
[英]How to replace text within a string based on their indices
我有一串來自數據庫的文本。 我還有一個數據庫鏈接列表,它有一個起始索引和長度與我的字符串相對應。 我想將文本中的鏈接附加為鏈接
<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將成為鏈接,第二次將鏈接中的鏈接...鏈接。
我顯然可以找到第一個索引,但是如果我在那個時候改變它,那么索引就不再有效了。
有沒有一種簡單的方法可以做到這一點,還是我錯過了什么?
您只需要使用String.Remove從源中刪除主題 ,然后使用String.Insert插入替換字符串。
正如@hogan在評論中建議的那樣,您需要對替換列表進行排序並以相反的順序(從最后到第一個)進行替換以使其正常工作。
如果您需要在單個字符串中執行許多替換,我建議使用StringBuilder
以提高性能。
這是沒有Remove
或Insert
或正則表達式的解決方案。 只是補充。
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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.