如何在2个不同的字符串中定界/提取字符串的一部分. [英] How to delimit / extract part of a string within 2 different strings.
问题描述
我想提取第一个单词",它实际上是要解析为另一种方法的主机名.我目前对其进行了硬编码.无论如何,要对其进行软编码以在"//"和&"之间获取数据. "/".使用VB.NET谢谢!.
Hi I want to extract the first "word" which is actually a host name to parse into another method. I currently hard coded it. Is there anyway to soft code it to take data between "//" & "/". Using VB.NET thanks!.
Dim s As String
Dim a As String
Dim f As String
For Each s In readText
If s.Trim.StartsWith("#") Then
SourceTextBox.Text = s.TrimStart("#")
s = s.TrimStart("#")
f = s.Substring(2)
Dim j As Integer = f.IndexOf("/")
a = f.Substring(0, j)
End if
If s.Trim.StartsWith("!") Then
TargetTextBox.Text = s.TrimStart("!")
s = s.TrimStart("!")
f = s.Substring(2)
Dim j As Integer = f.IndexOf("/")
a = f.Substring(0, j)
End If
这是文本文件
This is the text file
#//ASUS-PC/Users/Username/Desktop/Rays
!//DELL-PC/Users/Username/Desktop/Advan
所以我的输出是字符串"a"是
华硕PC
戴尔PC
但是我想对其进行软编码以更好地进行错误检查.由于目前我从每个行的开头开始对其进行硬编码.
So my output is string "a" is
ASUS-PC
DELL-PC
But I want to soft-code it for better error checking. Since currently I hard-code it to count from the start of each line.
推荐答案
是这样的:
It''s this:
static string ExtractComputerName(string fileName) {
string[] parts = fileName.Split(
new char[] { System.IO.Path.PathSeparator },
System.StringSplitOptions.RemoveEmptyEntries);
return parts[0];
}
注意:由于System.IO.Path.PathSeparator
,即使"\"也没有硬编码.
请参阅:
http://msdn.microsoft.com/en-us/library/system. io.path.pathseparator.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.string. split.aspx [^ ],
http://msdn.microsoft.com/en-us/library/ms131448.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx [^ ].
下次,请尝试更全面地探索MSDN,以找到可以帮助您的所有内容-这不是火箭手术. :-)
Pay attention: even "\" was not hard-coded, thanks to System.IO.Path.PathSeparator
.
Please see:
http://msdn.microsoft.com/en-us/library/system.io.path.pathseparator.aspx[^],
http://msdn.microsoft.com/en-us/library/system.string.split.aspx[^],
http://msdn.microsoft.com/en-us/library/ms131448.aspx[^],
http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx[^].
Next time, try to explore MSDN more thoroughly, to find all what can help you — it''s not rocket surgery. :-)
尝试一下,
try this,
Dim Result As string=""
Dim str = "#//ASUS-PC/Users/Username/Desktop/Rays"
Dim doubleSlashInd = str.IndexOf("//") + 2
Dim FirstSingleSlashAfterDoubleInd = str.IndexOf("/", doubleSlashInd)
Result = str.Substring(doubleslashInd, FirstSingleSlashAfterDoubleInd - doubleslashInd)
'result= asus-pc same way it will give result for dell-pc
祝您编码愉快!
:)
Happy Coding!
:)
这篇关于如何在2个不同的字符串中定界/提取字符串的一部分.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!