【问题标题】:C# How to add string elements in array to stringC#如何将数组中的字符串元素添加到字符串中
【发布时间】:2009-12-27 16:47:40
【问题描述】:

需要帮助才能执行此操作。或者关于如何将字符串添加到数组中的字符串元素的建议?

  1. 我们有 2 个 txt 文件,每个文件包含 100 个或更多字符串:

    域名.txt
    域1
    域2
    ..
    标题.txt
    标题1
    倾斜2
    ..

  2. 我们有:

    字符串链接=标题

  3. 读取文件后,我们将有 2 个字符串数组 - 我们需要将 domain.com 替换为 domain.txt 中的每个字符串,并将 title 替换为 title.txt 中的每个字符串,如下所示:

    title1
    title2
    ..

  4. 以这种方式将结果字符串数组保存到2个txt文件中:从1-50个字符串到
    1.txt和从50-100到2.txt的文件

用字符串数组元素操作字符串的最佳方法是什么?

【问题讨论】:

  • 这很琐碎,对不起,我会让其他人回答。请记住,字符串是不可变的,因此您需要执行 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 个?

标签: c# arrays string


【解决方案1】:

这可能是读取文件最简单的方法:

    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());

如果您的模板是一个参数,您可能希望动态构造格式字符串,而不是对其进行硬编码。以下是您如何做到这一点的示例:

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());
    }
}

【讨论】:

  • 这是一种形成字符串的方式,但我认为提问者想要修改现有模板,这可能不是最好的方式。
  • 问题:ReadAllInes 是否像使用“使用”+ IDisposable 那样自动关闭和处置资源?
  • @lpthnc:是的,ReadAllLines 使用 using 块。您可以在反射器中看到这一点。该实现实际上是在using 块中打开StreamReader,一次读取一行并将它们添加到ArrayList。然后返回使用ArrayList.ToArray(typeof(string)) 转换为string[] 的ArrayList。
  • @lpthnc:请参阅评论末尾的更新,以解决您的观点。
【解决方案2】:

使用 LINQ 和来自File 的一些不错的方法非常漂亮:

string[] domains = File.ReadAllLines(@"C:/domains.txt");
string[] titles = File.ReadAllLines(@"C:/titles.txt");
if(domains.Length != titles.Length) { throw new InvalidOperationException(); }
string link = "<a href=\"http://www.{0}.com\" target=\"_blank\">{1}</a>";
var results = domains.Select((domain, i) => String.Format(link, domain, titles[i]));
File.WriteAllLines("results1.txt", results.Take(results.Length / 2).ToArray());
File.WriteAllLines("results2.txt", results.Skip(results.Length / 2).ToArray());

如果有超过 100 个域/标题对,不清楚您想要什么,所以我将它们分成两半。

【讨论】:

  • 有了 Zip 后,.NET 4.0 更加优雅。
【解决方案3】:

另一种方法是像这样懒惰地做:

        static IEnumerable<string> ReadLinesLazily(string file)
    {
        using (var reader = new StreamReader(file))
        {
            string line = null;
            while ((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }

    static void Combine()
    {
        const string link = "<a href=\"{0}\">{1}</a>";
        var links = ReadLinesLazily("domains.txt").Zip(ReadLinesLazily("titels.txt"), (d, t) => String.Format(link, d, t))
        // write links here
    }

【讨论】:

  • 值得一提的是 Zip 首先包含在 .NET 4.0 中。
猜你喜欢
  • 1970-01-01
  • 2012-10-02
  • 2015-03-09
  • 2021-12-30
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 2020-03-08
相关资源
最近更新 更多