您可以使用以下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%
省略,则从字符串的开头开始搜索。您要查找的字符是CHR$(10)
. QBasic 使用这种 CHR 语法而不是 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
count 方法仅适用于 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