C# - 在字符串中存储多个值

时间:2018-01-24 12:33:03

标签: c#

我是C#的新手,所以请放轻松我...基本上,我正在阅读一个文本文件并希望在两个字符串之间获取任何数据并将所有这些数据存储到一个字符串中/ variable - 我该怎么做呢?

我已经得到了以下内容,但只需要朝着正确的方向努力让我重回正轨。

非常感谢

C#代码:

bool DetailsFound = false;
string[] ReadLines = File.ReadAllLines(path);
foreach (string item in ReadLines) {
    if (item == "Start Details") {
        DetailsFound = true;
    }
    if (DetailsFound) {
        Console.WriteLine("Details - " + item);
        // VARIABLE / STRING REQUIRED HERE
    }
    if (item == "End Details") {
        break;
    }
}

示例* .TXT文件

Start Details
I am line 1
I am line 2
I am line 3
End Details

7 个答案:

答案 0 :(得分:3)

您需要按正确的顺序执行所有操作 使用类似StringBuilder的内容来存储字符串。

var detailsFound = false;
var readLines = File.ReadAllLines(path);
var stringB = new StringBuilder();
foreach (string item in readLines) {
    if (item == "Start Details") {
        detailsFound = true;
    }
    else if (item == "End Details") {
        break;
    }
    else if (detailsFound) {
        Console.WriteLine("Details - " + item);
        stringB.AppendLine(item);
    }
}

答案 1 :(得分:1)

首先,您需要修正逻辑以正确处理结束(这是执行顺序的问题)。

然后,使用StringBuilder连接字符串:

StringBuilder sb = new StringBuilder();

foreach (string item in ReadLines) {
    if (item == "Start Details") {
        DetailsFound = true;
    }
    else if (item == "End Details") {
        break;
    }
    else if (DetailsFound) {
        Console.WriteLine("Details - " + item);
        sb.AppendLine(item);
        // VARIABLE / STRING REQUIRED HERE
    }
}

string output = sb.ToString();

如果您想让这些行成为单独的值,请使用List<string>

List<string> list = new List<string>();

foreach (string item in ReadLines) {
    if (item == "Start Details") {
        DetailsFound = true;
    }
    else if (item == "End Details") {
        break;
    }
    else if (DetailsFound) {
        Console.WriteLine("Details - " + item);
        list.Add(item);
        // VARIABLE / STRING REQUIRED HERE
    }
}

// list holds all lines

答案 2 :(得分:1)

很少有评论:

  • 您应该查看General Naming Conventions
  • 的MSDN
  • 使用File.ReadAllLines会将文件中的所有行加载到内存中。在这种情况下,我不认为我们想要这样做,因为我们可能会在几行后停止。考虑使用File.ReadLines

您获得了大量使用常规枚举的答案,这对于C#初学者来说非常棒,因为它对其他语言来说应该很熟悉。我想向您展示一个强大的C#功能LINQ

您可以按以下方式执行任务:

    public static void TakeBetween(string filePath, string startText, string endText)
    {
        var data = File.ReadLines(filePath).SkipWhile(line => !line.Contains(startText)).Skip(1).TakeWhile(line => !line.Contains(endText));
        // Do whatever that is needed with data. It is of type IEnumerable<string>
    }

您可以使用您想要的任何其他字符串查找方法替换.Contains。请注意,这不会将不必要的数据加载到内存中。

相关LINQ函数:

答案 3 :(得分:0)

你离得太远了。

对您的代码进行一些小修改:

List<string> results = new List<string>();

foreach (string item in ReadLines) 
{
    if (item == "Start Details") 
    {
        DetailsFound = true;
    }
    else if (item == "End Details") {
        break;
    }
    else if (DetailsFound) 
    {
        Console.WriteLine("Details - " + item);
        results.Add(item);
    }

}

这将存储列表中的字符串。现在您可以根据需要处理它们。例如,您可以将它们全部放在一个以逗号分隔的字符串中:

var commaSeparated = String.Join(results, ", ");

答案 4 :(得分:0)

请尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace Oppgave3Lesson1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            string input = "";
            List<string> lines = new List<string>();
            StreamReader reader = new StreamReader(FILENAME);

            Boolean foundStart = false;
            while ((input = reader.ReadLine()) != null)
            {
                if (!foundStart)
                {
                    if(input.StartsWith("Start")) foundStart = true;
                }
                else
                {
                    if (input.StartsWith("End")) break;
                    lines.Add(input);
                }
            }

        }
    }
}

答案 5 :(得分:0)

如果你想在一些特定的字符串后输出行,我会这样做

const string _startIdentifier = "Start Details"
const string _endIdentifier = "End Details"

private bool detailsFound
private List<string> details

foreach (string item in File.ReadAllLines(path)) {
    if (!detailsFound && item.Equals(_startIdentifier) {
        detailsFound = true;
    }

    if (item.Equals(__endIdentifier){
        break;
    }

    if (detailsFound) {
        details.Add(item);
        Console.WriteLine("Details - " + item);
    }
}

然后,如果您想将这些项目合并为一个字符串

var combinedItems = String.Join(", ", items)

这将创建一个看起来像“我是第1行,我是第2行,我是第3行”的字符串。当然,您可以使用Environment.NewLine

将分隔符从逗号更改为新行

答案 6 :(得分:0)

项在foreach循环中定义,并引用读取行。 您必须在循环之前定义一个字符串变量并附加每个项目。

string WriteDataHere = String.Empty; // <- 

bool DetailsFound = false;
string[] ReadLines = File.ReadAllLines(path);
foreach (string item in ReadLines) {
    if (item == "Start Details") {
    DetailsFound = true;
}
if (DetailsFound) {
    Console.WriteLine("Details - " + item);
    // VARIABLE / STRING REQUIRED HERE
    WriteDataHere += item; // <--
    }
    if (item == "End Details") {
        break;
    }
}

但是这个解决方案会导致一个看起来像这样的字符串:

  

我是第1行第2行是第3行

一种可能的解决方案是检查此字符串是否为空并添加换行符,如果代码行看起来有点不同:

if( String.isNullOrEmpty(WriteDataHere) == false)
   WriteDataHere += "\n";

WriteDataHere += item; // <--

更好的解决方案是将所有“项目”保存在列表

List<string> listOfStrings = new List<string>();

并通过Add-Method在每次迭代中添加每个项目。

但这取决于你打算用字符串做什么。