如何在文本文件中组合2个或更多字符串

时间:2012-06-21 16:48:21

标签: c# text-files

我一直试图找到一种方法来组合单个文本文件中的2个字符串。我正在阅读的文本文件具有以下格式:

String 1
String 2
String 3
...等等。 示例代码:

public static IEnumerable<string> getMeaningfulLines(string filename)
    {
        System.IO.StreamReader file =
          new System.IO.StreamReader(filename);
        while (!file.EndOfStream)
        {

            yield return file.ReadLine();
            yield return file.ReadLine();

            file.ReadLine();
            file.ReadLine();
            file.ReadLine();
            file.ReadLine();
        }
    }

    static void Main(string[] args)
    {


        foreach (string line in getMeaningfulLines(@"C://Log.txt"))
        {




            string teststring = line;

            string[] parts = line.Split(' ', ',', '-', '>', '[', ']');
            StringBuilder builder = new StringBuilder();


            foreach (string h in parts)
            {
                builder.Append(h).Append(" ");

            }

            string result = builder.ToString();
            string cleanedString = System.Text.RegularExpressions.Regex.Replace(result, @"\s+", " ");
            string trimString = cleanedString.Trim();

            trimString = trimString.Remove(trimString.Length - 1);


            //Console.WriteLine(trimString);

            string[] parts2 = trimString.Split(' ');
            string quotedstring = "'" + string.Join("','", parts2) + "'";
            //Console.WriteLine(quotedstring);
            string[] parts3 = quotedstring.Split(' ');
            Console.WriteLine(quotedstring, quotedstring.Length);
            //Console.WriteLine("1) The length of '{0}' is {1}",  quotedstring, quotedstring.Length);

我想将字符串2追加到字符串1,以便:“String1 String2”。我尝试使用split方法并使用字符串生成器附加它们。但是,这不起作用,因为它执行拆分和每行附加。我也不能用“。”将它们组合起来,因为它们不存储在变量中。有谁知道如何实现这个或一个例子?谢谢。

2 个答案:

答案 0 :(得分:6)

  

我正在阅读的文本文件格式如下:
  字符串1
  字符串2
  字符串3 ...等。我想将字符串2追加到字符串1,以便:“String1 String2”。

如果您想在文件中追加每一行,并在它们之间留一个空格,请执行以下操作:

string[] lines = File.ReadAllLines("my_file.txt");
string result = string.Join(" ", lines);

如果文件的行有结构,那么你可以定义一个类来保存这个结构,例如:

class Company
{
  private string name;
  private int id; 
  private string city;
  private string state;

  public string Name { get { return name; } }
  public int Id  { get { return id; } } 
  public string City { get { return city; } }
  public string State { get { return state; } }

  public Company(string name, int id, string city, string state) 
  {
    this.name = name;
    this.id = id;
    this.city = city;
    this.state = state; 
  }

  public override string ToString() 
  {
    // Create a formatted string from the fields here, for example:
    return name + " " + id + " " + city + " " + state;
  }

  public static Company FromLine(string line)
  {
    // Extract the fields from a line, and post-process the fields here, for example:
    string[] tokens = line.Split(separators);
    string name = tokens[0].Trim();
    int id = Convert.ToInt32(tokens[1]);
    string city = tokens[2];
    string state = tokens[3];
    return new Company(name, id, city, state);
  }
}

此类可用于提取每一行的字段,格式化它们,并附加这些格式化的字符串:

string[] lines = File.ReadAllLines("my_file.txt");
List<Company> companies = new List<Company>();
foreach (string line in lines)
  companies.Add(Company.FromLine(line));
string result = string.Join(" ", companies);

您甚至可以指定要追加的项目,只需修改最后一行,例如像这样:

string result = string.Join(" ", companies.Where(company => company.Id > 10));

答案 1 :(得分:1)

以下应该做你想要的,但根据文件的大小等可能不合适,这就是为这种事情提供上下文的重要性。这是我能想到的最快捷的方式。

string[] lines = File.ReadAllLines(filePath);
string joinedString = String.Format("{0} {1}", lines[0], lines[1]);