我有一个相当复杂的字符串,我需要从中提取。从字符串提取
字符串 - !0A!0B!0C @[email protected]@0B
我想读取每个!
,并提取它们作为一组的3含义!0A
,!0B
,!0C
然后我打算使用选择的情况下阅读它们,因为每个人代表什么(是否会选择情况是好?)
以及如何提取它们在3S
我有一个相当复杂的字符串,我需要从中提取。从字符串提取
字符串 - !0A!0B!0C @[email protected]@0B
我想读取每个!
,并提取它们作为一组的3含义!0A
,!0B
,!0C
然后我打算使用选择的情况下阅读它们,因为每个人代表什么(是否会选择情况是好?)
以及如何提取它们在3S
这个方法应该做的伎俩。发送你的字符串,结果列表将出来:
public List<string> StringParser(string s){
var list = new List<string>();
for(int i = 0; i < s.Length; i++){
if(s[i] == '!'){
list.Add(s.Substring(i,3));
i+= 2;
}
}
return list;
}
请注意,如果字符串包含一个!在它之后至少没有其他两个字符,所以你应该在实际运行substring命令之前执行一个测试来验证这一点。
如果你需要做的是,在你的代码中的许多地方,你可以创建一个花哨的扩展方法:
static class StringExtensions {
public static IEnumerable<String> SplitInParts(this String s, Int32 partLength) {
if (s == null)
throw new ArgumentNullException("s");
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", "partLength");
for (var i = 0; i < s.Length; i += partLength)
yield return s.Substring(i, Math.Min(partLength, s.Length - i));
}
}
然后,您可以使用它像这样:
var parts = "!0A!0B!0C @[email protected]@0B".SplitInParts(3);
我会用常规表达。例如像这样:
Dim str As String = "!0A!0B!0C"
Dim ptr As String = "[!][A-Z0-9]{2}"
Dim matches As MatchCollection = Regex.Matches(str, ptr)
For Each m In matches
Console.WriteLine(m.ToString())
Next
对不起,该示例是在VB中,但你从中得到的想法。