简体   繁体   English

如何在字符串中的特定字符串后插入字符串?

[英]How do I insert a string AFTER a specific string within a string?

I know, I know, I probably confused you! 我知道,我知道,我可能会困惑你! :) :)

I have this: 我有这个:

namespace WebPageHeaderFixer
{
    class Program
    {
        static void Main(string[] args)
        {
            string folderToSearch = @"C:\Test\";

            foreach (string file in Directory.GetFiles(folderToSearch))
            {
                string fileString = File.ReadAllText(file);

                //Here, I want to insert string X into "fileString" AFTER string Y.
            }
        }
    }
}

I want to add the string X into the variable fileString after the LAST Register TagPrefix: 我想在LAST Register TagPrefix之后将字符串X添加到变量fileString中:

<%@ Register TagPrefix="ucCal" TagName="popupCalendar" Src="../UserControls/popupCalendar.ascx" %>
<%@ Register TagPrefix="ucRes" TagName="Search" Src="../UserControls/SearchControl.ascx" %>
<%@ Register TagPrefix="abc" TagName="header" Src="../Header.ascx" %>
//I want to insert X here
other code
some more code
some ugly code

How do I go about doing this? 我该怎么做呢?

*Please note that the last Register tag might be different between files. *请注意,文件之间的最后一个Register标记可能不同。

Can you read the file line by line instead of a single string? 你能逐行而不是单个字符串读取文件吗? You could then cycle through the lines to find the last occurrence of the string you are interested in, then you can write the lines back to the file, inserting your string after it. 然后,您可以遍历这些行以查找您感兴趣的字符串的最后一个匹配项,然后您可以将这些行写回文件,然后在其后面插入字符串。

Using insert method and indexof method and lastindexof method it can be done like this: 使用insert方法和indexof方法以及lastindexof方法可以这样做:

int LastRegister = fileString.LastIndexOf("Register TagPrefix");
int InsertPosition = fileString.IndexOf('>', LastRegister) + 2;
fileString = fileString.Insert(InsertPosition, "String x");

This sets the insert position 2 characters past the index of the '>' following the last occurrence of "Register TagPrefix", which should put the insert position at the start of the next line. 这将插入位置设置为超过最后一次出现的“Register TagPrefix”之后的'>'的索引,这应该将插入位置放在下一行的开头。 If the string has 2 characters for end of line you may have to offset the insert position by one more. 如果字符串的末尾有2个字符,则可能需要将插入位置偏移一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM