qbasic中的新行char?

问题描述 投票:1回答:2

我知道我的问题非常基本,但我对qbasic并不熟悉,所以请原谅。我的问题是:

我如何在qbasic中检测字符串变量中的新行char?在java中我们必须找到'\n' char,但qbasic是什么?真的我想读取一个文本文件并检测它的行。谢谢。

newline qbasic
2个回答
2
投票

你可以使用INSTR函数:

'Sample text
Dim myText As String
myText = "Hello World!" + CHR$(10) + "This is a new line."

'Find new line character \n (line feed LF)
Dim newLinePosition As Integer
newLinePosition = Instr(myText, CHR$(10))
If (newLinePosition >= 1) Then
    Print "Yes, a LF character was found at char no# "; Ltrim$(Str$(newLinePosition))
Else
    Print "No LF character was found. :("
End If

Sleep: End

INSTR的语法如下所示:

pos% = INSTR ( [startOffset%,] haystack$, needle$ )

如果省略startOffset%,它将在String的开头处开始搜索。你寻找的角色是CHR$(10)。 QBasic使用这个CHR-Syntax而不是Java等已知的转义。

在这里您可以找到有关INSTR功能的其他帮助:

如果您只想计算文本文件的行数而不是在字符串中查找LF字符,则可以执行以下操作:

Dim lineCount As Integer
lineCount = 0

Dim f As Integer
f = FreeFile  ' Automatic detection of next free file handle

Open "MYTEXT.TXT" For Input As #f
Do Until Eof(f)
    Line Input #f, temp$
    lineCount = lineCount + 1
Loop
Close #f

Print "The text file consists of "; Ltrim$(Str$(lineCount)); " lines."
Sleep: End

但请注意:LINE INPUT计数方法仅适用于DOS / Windows行结尾(CrLf = Chr $(13)+ Chr $(10)= \ r \ n)。如果文本文件具有类似UNIX的行结尾(仅限\ n),则文件中的所有行将成为单个字符串,并且上面的计数脚本将始终返回“1行”作为结果。

在这种情况下,另一种方法是在BINARY模式下打开文件并逐字节地检查它。如果遇到Chr $(10),则行计数变量递增。

DIM lineCount AS INTEGER
lineCount = 0

DIM f AS INTEGER
f = FREEFILE  ' Automatic detection of next free file handle

DIM buffer AS STRING
buffer = SPACE$(1)

OPEN "MYTEXT.TXT" FOR BINARY AS #f
DO UNTIL EOF(f)
    GET #f, , buffer
    IF (buffer = CHR$(10)) THEN
        lineCount = lineCount + 1
    END IF
LOOP
CLOSE #f

PRINT "The text file consists of "; LTRIM$(STR$(lineCount)); " lines."
SLEEP: END

0
投票

用于使用二进制文件i / o计算文件中的行的示例程序。

REM sample program to count lines in a file in QB64.
' declare filename buffer
CONST xbuflen = 32767 ' can be changed
DIM SHARED xbuffer AS STRING * XBUFLEN
DIM SHARED Lines.Counted AS DOUBLE
' get filename
PRINT "Enter filename";: INPUT Filename$
' start file count
IF _FILEEXISTS(Filename$) THEN
    X = FREEFILE
    OPEN Filename$ FOR BINARY SHARED AS #X LEN = xbuflen
    IF LOF(X) > 0 THEN
        DO UNTIL EOF(X)
            ' get file buffer
            GET X, , xbuffer
            ' count bytes in buffer
            FOR L = 1 TO xbuflen
                IF MID$(xbuffer, L, 1) = CHR$(10) THEN
                    Lines.Counted = Lines.Counted + 1#
                END IF
            NEXT
        LOOP
    END IF
    CLOSE #X
END IF
PRINT "Lines in file"; Lines.Counted
END
© www.soinside.com 2019 - 2024. All rights reserved.