foreach(string s in lst)
{
if(s.StartsWith("[") && s.EndsWith("]"))
{
//add to OuterBracket_List
OuterBracket_List.Add(s);
}
else
{
int n;
if (int.TryParse(s, out n) == false)
{
//add AlphaNumeric_List
AlphaNumeric_List.Add(s);
}
else
{
//add n to Numeric List
}
}
}
更新 1:
上面的代码处理用括号 [] 括起来的字母数字、数字和字符串。
更新 2:
可能这里的所有解决方案都包括数值,即AlphaNumeric_List 中的12、15 和ABC:
但也只有字母类别,但我已将您的列表区分为 3 类字符串:
- 字符串
enclosed in brackets 例如。 “[ABC]”
- 字符串
containing Alpha-numeric 例如。 "ab 1"
- 字符串
containing numeric characters 仅限 ex。 12
这里是更新的代码:
foreach (string s in lst)
{
if (s.StartsWith("[") && s.EndsWith("]"))
{
//add to OuterBracket_List
OuterBracket_List.Add(s);
}
else
{
int n;
if (int.TryParse(s, out n) == false && isAlphaNumeric(s))
{
//add AlphaNumeric_List
AlphaNumeric_List.Add(s);
}
else
{
//add n to Numeric List if required
}
}
}
//method to check string is AlphaNumeric Note: Regex can be used
public bool isAlphaNumeric(string strToCheck)
{
for (int i = 0; i < strToCheck.Length; i++)
{
if (char.IsLetter(strToCheck[i]) == false)
{
return true;
}
}
return false;
}
这里是输入:
List<string> lst = new List<string>() { "ABC", "[ABC]", "AB[c", "AB]C",
"ab 1", "12a", "ab1", "[abc 1]",
"12", "15", "[XYZ-12ac]", "ab 1",
"[233]" };
这是输出:
OuterBracket_List = {"[ABC]", "[abc 1]", "[XYZ-12ac]", "[233]"}
AlphaNumeric_List = {"AB[c", "AB]C", "ab 1", "12a", "ab1", "ab 1"}