【问题标题】:C# String append some string ater first occurance of a string after a given stringC# String 在给定字符串后第一次出现字符串后追加一些字符串
【发布时间】: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 方法。检查IndexOfInsert等...
  • @PrasadTelkikar 我认为这一点是由 OP 明确指定的:在 first 出现之后附加,所以你的例子的结果是:This text is a textreplace of text string
  • 使用 Split(new string[] { "text" }, StringSplitOptions.None) 然后你就可以完全控制它了

标签: c# string extension-methods string-operations


【解决方案1】:

您必须找到要匹配的第一个单词的索引,然后使用该索引从该索引开始再次搜索第二个单词,然后您可以插入新文本。您可以使用 IndexOf method 找到所述索引(检查它的重载)。

这是一个简单的解决方案,以一种(我希望)可读的方式编写,并且您可以改进以使其更符合习惯:

    public static string AppendFirstOccurranceAfter(this string originalText, string after, string oldValue, string newValue) {
    var idxFirstWord = originalText.IndexOf(after);
    var idxSecondWord = originalText.IndexOf(oldValue, idxFirstWord);
    var sb = new StringBuilder();

    for (int i = 0; i < originalText.Length; i++) {
        if (i == (idxSecondWord + oldValue.Length))
            sb.Append(newValue);
        sb.Append(originalText[i]);
    }

    return sb.ToString();
}

【讨论】:

    【解决方案2】:

    扩展方法如下:

            public static string CustomReplacement(this string str)
            {
                string find = "text"; // What you are searching for
                char afterFirstOccuranceOf = 'a'; // The character after the first occurence of which you need to find your search term.
                string replacement = "$1$2replace"; // What you will replace it with. $1 is everything before the first occurrence of 'a' and $2 is the term you searched for.
    
                string pattern = $"([^{afterFirstOccuranceOf}]*{afterFirstOccuranceOf}.*)({find})";
    
                return Regex.Replace(str, pattern, replacement);
            }
    

    你可以这样使用它:

    
    string test1 = "This is a text string".CustomReplacement();
    string test2 = "This text is a text string".CustomReplacement();
    
    

    此解决方案使用 C# 正则表达式。来自 Microsoft 的文档在这里:https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference

    【讨论】:

      最近更新 更多