检查字符串是否包含字符串数组的任何元素(vb net)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18952971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if string contains any of the elements of a stringarray (vb net)
提问by Reese Duchamps
I′ve got a little problem. At the end of a programm it should delete a folder.
我有一个小问题。在程序结束时,它应该删除一个文件夹。
In ordern to deny deletion of a folder, which directory contains a certain word, I wanted to check if a string (the directory.fullname.tostring) contains any of the elements which are stored in a string array. The string array contains strings stating the exception words.
为了拒绝删除文件夹,其中目录包含某个单词,我想检查一个字符串(目录.fullname.tostring)是否包含存储在字符串数组中的任何元素。字符串数组包含说明异常词的字符串。
This is how far I got and I know that the solution is the other way round than stated here:
这是我得到的程度,我知道解决方案与此处所述相反:
If Not stackarray.Contains(dir.FullName.ToString) Then
Try
dir.Delete()
sw.WriteLine("deleting directory " + dir.FullName, True)
deldir = deldir + 1
Catch e As Exception
'write to log
sw.WriteLine("cannot delete directory " + dir.ToString + "because there are still files in there", True)
numbererror = numbererror + 1
End Try
Else
sw.WriteLine("cannot delete directory " + dir.ToString + "because it is one of the exception directories", True)
End If
采纳答案by Steven Doggart
Instead of checking to see if the array contains the full path, do it the other way around. Loop through all the items in the array and check if the path contains each one, for instance:
与其检查数组是否包含完整路径,不如反过来做。循环遍历数组中的所有项目并检查路径是否包含每个项目,例如:
Dim isException As Boolean = False
For Each i As String In stackarray
If dir.FullName.ToString().IndexOf(i) <> -1 Then
isException = True
Exit For
End If
Next
If isException Then
' ...
End If
Or, if you want to be more fancy, you can use the Array.Exists method to do it with less lines of code, like this:
或者,如果您想更花哨,可以使用 Array.Exists 方法以更少的代码行来完成,如下所示:
If Array.Exists(stackarray, Function(x) dir.FullName.ToString().IndexOf(x) <> -1) Then
' ...
End If

