读取文本文件并逐行分割。

huangapple go评论60阅读模式
英文:

Read and split line by line in text file

问题

我正在尝试从我的应用程序资源中读取文本文件。对于文本文件中的每一行,我想要在逗号之前和之后拆分文本。

txt文件中的每一行看起来像这样:

-125.325235,4845636

我的问题是该函数循环运行,不断重复执行for each语句。

对于每一行作为字符串在我的.Resources.CompanyBases
    MsgBox(My.Resources.CompanyBases.Split(","c).First)
    MsgBox(My.Resources.CompanyBases.Split(","c).Last)
下一个
英文:

I am trying to read a text file from my applications resources. For each line in this text file I want to split the text before and after the comma.

Each line in txt file looks like this:

-125.325235,4845636

My issue is that the function loops and does not end constantly repeating the for each statement

For Each Line As String In My.Resources.CompanyBases
    MsgBox(My.Resources.CompanyBases.Split(","c).First)
    MsgBox(My.Resources.CompanyBases.Split(","c).Last)
Next

答案1

得分: 1

首先,不要像那样一次又一次地获取资源。这些属性不是"实时"的。每次获取属性时,资源都必须从程序集中提取出来。如果您需要多次使用该值,请获取一次属性并将其分配给变量,然后多次使用该变量。

其次,您并没有获取文件。资源的整个目的是它们不是不同的文件,而是编译到程序集中的数据。它只是一个像任何其他字符串一样的 String。您通常如何在换行符上拆分字符串?

最后,您有一个带有循环控制变量 LineFor Each 循环,但在循环内部从未使用该变量。在循环内部应该拆分 Line,而不是包含所有行的资源属性。

For Each line In My.Resources.CompanyBases.Split({Environment.NewLine}, StringSplitOptions.None)
    Dim fields = line.Split(","c)

    Debug.WriteLine(fields(0))
    Debug.WriteLine(fields(1))
Next

请注意,如果您使用 .NET Core,Split 也将接受一个字符串数组,而不仅仅是一个字符串。

英文:

Firstly, don't ever get a resource over and over like that. Those properties are not "live". Every time you get the property, the resource has to be extracted from your assembly. If you need to use the value multiple times, get the property once and assign it to a variable, then use that variable over and over.

Secondly, you're not getting a file. The whole point of resources is that they are not distinct files but rather data compiled into your assembly. It's just a String like any other. How would you usually split a String on line breaks?

Finally, you have a For Each loop with a loop control variable Line, yet you never use that variable inside the loop. It should be Line that you're splitting inside the loop, not the resource property containing all the lines.

For Each line In My.Resources.CompanyBases.Split({Environment.NewLine}, StringSplitOptions.None)
    Dim fields = line.Split(","c)

    Debug.WriteLine(fields(0))
    Debug.WriteLine(fields(1))
Next

Note that, if you're using .NET Core, Split will accept a String as well as a String array.

huangapple
  • 本文由 发表于 2023年2月10日 15:17:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75407989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定