我正在从事迷你程序。我有一个字符串清单。我正在阅读.txt文件中的字符串,如果我的单词包含4个或更多字符,则可以阅读它。好的,这就是我有效的。然后,我需要在另一个文件中写下所有字符串(单词(,并且它很有效,但是我有问题。
例如,我有一个单词学校(6 char(,我需要从单词中修剪一些字符。例如
school = chool,hool等。程序= Rogram,Ogram,Gram等...
我需要得到这样的东西,这是代码。我的代码仅适用于第一个字符,但不适用于循环中的其他代码。
例如,我会得到程序= rogram,但不能,而不是ogram,gram等...我的问题是,如何从输入.txt文件中的单词列表中获取所有修剪单词,例如:
程序,学校,等
和输出.txt文件,我需要得到这样的东西:Rogram,ogram,公克,Chool,hool,
这是代码。
Dim path As String = "input_words.txt"
Dim write As String = "trim_words.txt"
Dim lines As New List(Of String)
'reading file'
Using sr As StreamReader = New StreamReader(path)
Do While sr.Peek() >= 4
lines.Add(sr.ReadLine())
Loop
End Using
'writing file'
Using sw As StreamWriter = New StreamWriter(write)
For Each line As String In lines
sw.WriteLine(line.Substring(1, 5))
Next
End Using
while loop
解决问题的简单方法是使用While
循环,而长度大于4
当我们当前的字符串超过4个长度时,这里:
- 我们写它
-
我们删除第一个字符
For Each line As String In lines Dim current As String = line While current.Length > 4 Console.Write(current & ",") current = current.Remove(0, 1) End While Console.Write(current & vbNewLine) Next
for循环
第二种方法是使用For
循环,其中想法是从当前单词的长度到(5(应用最后一个-1:
- 我们写它
-
我们删除第一个字符
For Each line As String In lines Dim current As String = line For i As Integer = line.Length To 5 Step -1 Console.Write(current & ",") current = current.Remove(0, 1) Next Console.Write(current & vbNewLine) Next
我做了一个不同的解决方案。因为我需要限制4个字符,所以我做了这个。
Dim path As String = "input_words.txt"
Dim write As String = "trim_words.txt"
Dim lines As New List(Of String)
'reading file'
Using sr As StreamReader = New StreamReader(path)
Do While sr.Peek() >= 4
lines.Add(sr.ReadLine())
Loop
End Using
'writing file'
Using sw As StreamWriter = New StreamWriter(write)
For Each line As String In lines
Dim iStringLength = line.Length
Dim iPossibleStrings = iStringLength - 5
For i = 0 To iPossibleStrings
Console.WriteLine(line.Substring(i, 4))
Next
Next
End Using
tnx提供帮助@Mederic!