如何检测字符串C#中的第3、4、5个字母
How to detect the 3rd, 4th, 5th letter in a string C#
我有一个 string
结构如下:
string s = "0R 0R 20.0V 100.0V 400.0R 60R 70.0R";
我的问题是,如何只检测 3rd、4th、5th像这样通过 if 语句来信:
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
我正在考虑使用 foreach 循环遍历字符串,但我不确定如何检测它何时是 3、4、5 字母,我知道 正则表达式 可能有帮助,但我不确定如何实现 表达式
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];
我有一个 string
结构如下:
string s = "0R 0R 20.0V 100.0V 400.0R 60R 70.0R";
我的问题是,如何只检测 3rd、4th、5th像这样通过 if 语句来信:
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
我正在考虑使用 foreach 循环遍历字符串,但我不确定如何检测它何时是 3、4、5 字母,我知道 正则表达式 可能有帮助,但我不确定如何实现 表达式
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];