【发布时间】:2024-04-24 14:05:02
【问题描述】:
我知道这似乎很复杂,但我的意思是例如我有一个字符串
This is a text string
我想搜索一个字符串(例如:文本)。我想找到这个字符串的第一次出现,它出现在给定的另一个字符串(例如:is)之后,并且替换应该是另一个给定的字符串(例如:replace)
所以结果应该是:
This is a textreplace string
如果文本是This text is a text string,那么结果应该是This text is a textreplace string
我需要一个方法(扩展方法表示赞赏):
public static string AppendFirstOccurranceAfter(this string originalText, string after, string oldValue, string newValue)
// "This is a text string".ReplaceFirstOccurranceAfter("is", "text", "replace")
【问题讨论】:
-
如果
text出现三次怎么办?This text is a text of text string的预期输出是什么 -
你有没有尝试过?您可以在等待某人发布答案时探索String 方法。检查
IndexOf、Insert等... -
@PrasadTelkikar 我认为这一点是由 OP 明确指定的:在 first 出现之后附加,所以你的例子的结果是:
This text is a textreplace of text string -
使用 Split(new string[] { "text" }, StringSplitOptions.None) 然后你就可以完全控制它了
标签: c# string extension-methods string-operations