当NewLine是分隔符时,可以使用String.Split()吗? [英] Is it possible to use String.Split() when NewLine is the delimiter?

查看:73
本文介绍了当NewLine是分隔符时,可以使用String.Split()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,要求我从输入文件中计算出一些内容.问题在于,文件中的行不使用任何特殊字符作为分隔符,例如 | .我将在下面显示.

 数据通信20Visual Basic40 

我需要写入另一个文件的输出应如下所示:

 数据通信20Visual Basic 40总书数:60 

问题是,如何指定分隔符?就像在 strArray = strLine.Split(,")中出现符号一样.既然没有什么可以用作分隔符,那么如何分割文件内容?

解决方案

当您可以使用标准方法逐行读取文件时,实际上不需要拆分输入文件中的文本.

您可以使用例如 StreamReader 要从源文件中读取行,请使用

现在,您有了一个词典,其中的键代表类别,而相关的值是该类别中所有书籍的总和.

您可以 Select()字典中的每个KeyValuePair,并将其转换为代表键及其值的字符串( Category:Number ).
在这里,还使用 OrderBy(),以升序按字母顺序排列类别;这可能很有用.

然后,

File.WriteAllLines 调用以存储生成的字符串.
最后,使用 Sum()方法将所有字典中的值.

  Dim newFilePath = Path.Combine(basePath,"BooksNew.txt")File.WriteAllLines(newFilePath,booksDict.Select(Function(kvp)$"{kvp.Key}:{kvp.Value}').OrderBy(Function s))File.AppendAllText(newFilePath,vbCrLf&< Total Books:" booksDict.Sum(Function(kvp)kvp.Value).ToString()) 

输出为:

  C#:100C ++:10000数据通讯:20其他东西:3Visual Basic:50总书数:10173 

I have a question which asks me to calculate something from an input file. The problem is, the lines in the file don't use any special character as delimiter, like , or |. I will show it down below.

Data Communication 
20 
Visual Basic  
40

The output I need to write to another file should look like this:

Data communication 20
Visual Basic 40

Total Books : 60

The problem is, how can I specify the delimiter? Like when there is a symbol as in strArray = strLine.Split(","). Since there is nothing I can use as delimiter, how can I split the file content?

解决方案

There's no real need to split the text in the input file, when you can read a file line by line using standard methods.

You can use, e.g., a StreamReader to read the lines from the source file, check whether the current line is just text or it can be converted to a number, using Integer.TryParse and excluding empty lines.

Here, when the line read is not numeric, it's added as a Key in a Dictionary(Of String, Integer), unless it already exists (to handle duplicate categories in the source file).
If the line represents a number, it's added to the Value corresponding to the category Key previously read, stored in a variable named previousLine.

This setup can handle initial empty lines, empty lines in the text body and duplicate categories, e.g.,

Data Communication
20 
Visual Basic  
40

C#  
100
Visual Basic  
10
Other stuff
2

C++
10000
Other stuff
1

If a number is instead found in the first line, it's treated as a category.
Add any other check to handle a different structure of the input file.

Imports System.IO
Imports System.Linq

Dim basePath = "[Path where the input file is stored]"
Dim booksDict = New Dictionary(Of String, Integer)
Dim currentValue As Integer = 0
Dim previousLine As String = String.Empty

Using sr As New StreamReader(Path.Combine(basePath, "Books.txt"))

    While sr.Peek > -1
        Dim line = sr.ReadLine().Trim()
        If Not String.IsNullOrEmpty(line) Then
            If Integer.TryParse(line, currentValue) AndAlso (Not String.IsNullOrEmpty(previousLine)) Then
                booksDict(previousLine) += currentValue
            Else
                If Not booksDict.ContainsKey(line) Then
                    booksDict.Add(line, 0)
                End If
            End If
        End If
        previousLine = line
    End While
End Using

Now, you have a Dictionary where the Keys represent categories and the related Value is the sum of all books in that category.

You can Select() each KeyValuePair of the Dictionary and transform it into a string that represents the Key and its Value (Category:Number).
Here, also OrderBy() is used, to order the categories alphabetically, in ascending order; it may be useful.

File.WriteAllLines is then called to store the strings generated.
In the end, a new string is appended to the file, using File.AppendAllText, to write the sum of all books in all categories. The Sum() method sums all the Values in the Dictionary.

Dim newFilePath = Path.Combine(basePath, "BooksNew.txt")

File.WriteAllLines(newFilePath, booksDict.
    Select(Function(kvp) $"{kvp.Key}:{kvp.Value}").OrderBy(Function(s) s))
File.AppendAllText(newFilePath, vbCrLf & "Total Books: " & booksDict.Sum(Function(kvp) kvp.Value).ToString())

The output is:

C#:100
C++:10000
Data Communication:20
Other stuff:3
Visual Basic:50

Total Books: 10173

这篇关于当NewLine是分隔符时,可以使用String.Split()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆