这可能是读取文件最简单的方法:
string[] domains = File.ReadAllLines("domain.txt");
string[] titles = File.ReadAllLines("titles.txt");
为了使替换你可以使用string.Format
:
int n = domains.Length;
string[] results = new string[n];
for (int i = 0; i < n; ++i)
{
results[i] = string.Format(
@"<a href=""http://{0}"" target=""_blank"">{1}</a>",
domains[i], titles[i]);
}
要写出你可以使用输出的Linq:
File.WriteAllLines("file1.txt", results.Take(n/2).ToArray());
File.WriteAllLines("file2.txt", results.Skip(n/2).ToArray());
如果你的模板是一个参数,你可能想要构造格式str动态而不是硬编码。这里是你如何能做到这一点的例子:
using System;
using System.IO;
using System.Linq;
class Program
{
static string escapeBraces(string s)
{
return s.Replace("{", "{{").Replace("}", "}}");
}
static string createFormatString(string template, params string[] parameters)
{
template = escapeBraces(template);
for (int i =0; i < parameters.Length; ++i) {
template = template.Replace(
escapeBraces(parameters[i]),
"{" + i + "}");
}
return template;
}
static void Main(string[] args)
{
string template = @"<a {}href=""http://www.domain.com"" target=""_blank"">title</a>";
string formatString = createFormatString(template, "www.domain.com", "title");
string[] domains = File.ReadAllLines("domain.txt");
string[] titles = File.ReadAllLines("title.txt");
int n = domains.Length;
if (titles.Length != n)
throw new InvalidDataException("There must be the same number domains and titles.");
string[] results = new string[n];
for (int i = 0; i < n; ++i)
{
results[i] = string.Format(formatString, domains[i], titles[i]);
}
File.WriteAllLines("file1.txt", results.Take(n/2).ToArray());
File.WriteAllLines("file2.txt", results.Skip(n/2).ToArray());
}
}
这是微不足道的,对不起,我让别人回答。请记住,字符串是不可变的,所以你会想做arr [12] = arr [12] .replace(“x”,“y”)而不仅仅是a = arr [12]; a.replace(“x”,“y”); (假设你把东西放在一个数组中)。 MSDN是你的朋友,代码完成也是如此。 –
你说“100或更多”,但后来你想在一个文件中使用1-50,在第二个文件中使用50-100。如果有超过100行的话,第二部分将如何工作?你想在每个文件中使用一半的文件,或者每个文件中最多只有50行文件,只需要多少个文件? –
感谢您的快速回复。从1-50节省的结果我只是想知道如何选择特殊线路保存,例如从第10个字符串到20? –