从数据库的值替换字符串

本文关键字:替换 字符串 数据库 | 更新日期: 2023-09-27 17:54:00

使用C#4.0vs10ASP.Net MVC 4.0

下面是一个示例字符串:

string x = "herr <FirstName> <LastName> , 'n With due respect and humble submission, I , the student of <Semester>,<Year> of <DepartmentName> of <UniversityName>."

我有一个有数百万行的数据库,里面有不同的(这些(信息。

我得检查一下绳子。在找到"<>"此标记的地方,对于数据表的每一行,"<>"标记内的字段都将被替换。我不明白我在说什么。请让我举一个例子:

对于数据表的每一行,当在字符串中找到时,将在此处替换当前DataRow中的FirstName。类似:

foreach(DataRow drow in dt.Rows)
{
    string body = "herr " + drow["FirstName"] + " " + drow["LastName"] + ", 'n With due respect and humble submission, I , the student of " + drow["Semester"] + "," + drow["Year"] + " of " + drow["DepartmentName"] + " of " + drow["UniversityName"] + ".";
sendmail(body);
}

我对RegularExpression一无所知。有什么简单、简单、明智的方法可以做到这一点吗?

从数据库的值替换字符串

一个简单的解决方案是使用Replace方法:

string x = "herr <FirstName> <LastName> , 'n With due respect and humble submission, I , the student of <Semester>,<Year> of <DepartmentName> of <UniversityName>."


foreach(DataRow drow in dt.Rows)
{
   string body = x.Replace("<FirstName>", drow["FirstName"]).
                Replace("<LastName>", drow["LastName"]).
                Replace("<Semester>", drow["Semester"]).
                Replace("<Year>", drow["Year"]).
                Replace("<DepartmentName>", drow["DepartmentName"]).
                Replace("<UniversityName>", drow["UniversityName"]);
    sendmail(body);
}

编辑:

如果"<>"标记之间的内容不是预先确定的,则可以使用以下扩展方法。

public static class StringExtensions
{
    public static string ReplaceString(this string s, string newString)
    {
        int startIndex = s.IndexOf("<");
        s = s.Insert(startIndex, newString);
        startIndex = s.IndexOf("<"); //redetermine the startIndex in a new string generated above
        int length = s.IndexOf(">") - startIndex + 1;
        return s.Remove(startIndex, length);
    }
}

该方法只需搜索第一个"<"和第一个">",并替换其中的标记和内容。您可以通过以下方式使用它:

string body = x.ReplaceString(drow["value for dynamicly defined tag"]).
  ReplaceString(drow["value for dynamicly defined tag 2"])

等等…

注意:

在上面的例子中,我本可以使用replace方法,而不是首先插入新值,然后删除标记,但由于标记中的内容可能取决于用户输入,因此两个标记可能具有相同的内容,在这种情况下,replace方法会造成麻烦。

字符串。我想Format是你的朋友。

一个例子:

string x = string.Format("herr {0} {1} , 'n With due respect and humble submission, I , the student of {2},{3} of {4} of {5}.", drow["FirstName"], drow["LastName"], drow["Semester"], drow["Year"], drow["DepartmentName"], drow["UniversityName"]);