我有一个string
,其结构类似:
string s = "0R 0R 20.0V 100.0V 400.0R 60R 70.0R";
我的问题是,我如何通过if语句只检测第三个、第四个、第五个 或通过打印报表: 我曾考虑使用foreach循环来循环字符串,但我不确定如何检测它是第三、第四、第五个字母,我知道正则表达式可能会有所帮助,但我也不确定如何实现表达式3rd letter = V
4th letter = V
5th letter = R
//pseudocode below
if (3rd letter in string == V)
{
return true;
}
if (4th letter in string == V)
{
return true;
}
if (5th letter in string == R)
{
return true;
}
3rd letter = V
4th letter = V
5th letter = R
// Pseudocode below:
Console.WriteLine("3rd Letter"); //should return V
Console.WriteLine("4th Letter"); //should return V
Console.WriteLine("5th Letter"); //should return R
string s = "0R 0R 20.0V 100.0V 400.0R 60R 70.0R";
foreach(char c in s)
{
// detect 3rd 4th 5th letter in here
}
首先,让我们借助Linq:提取/匹配字母
using System.Linq;
...
string[] letters = s
.Where(c => c >= 'A' && c <= 'Z')
.Select(c => c.ToString())
.ToArray();
或正则表达式:
using System.Linq;
using System.Text.RegularExpressions;
...
string[] letters = Regex
.Matches(s, "[A-Z]")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
然后你可以像一样简单
string letter3d = letters[3 - 1]; // - 1 : arrays are zero based
string letter4th = letters[4 - 1];
string letter5th = letters[5 - 1];