我正在制作迷你程序。我有一个字符串列表。我正在从.txt文件中读取字符串,如果我有一个包含4个或更多字符的单词,那么请阅读它。好的,我的工作正在进行中。然后我需要在另一个文件中写出所有字符串(单词),并且它正在工作,但我有问题。
例如我有一个单词School(6char),我需要从单词中修剪一些字符。例如
学校= chool,hool等。 程序= rogram,ogram,gram等......
我需要得到类似的东西,这里是代码。我的代码只适用于第一个char,但不适用于循环中的其他char。
例如,我将得到Program = 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
答案 0 :(得分:0)
解决问题的一种简单方法是在长度大于4时使用While
循环
这里我们当前的字符串长度超过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
循环,其中的想法是从当前单词的长度到(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
答案 1 :(得分:0)
我做了一个不同的解决方案。因为我需要限制为4个char我做了这个。
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!