【发布时间】:2020-08-03 20:27:36
【问题描述】:
我有一个string,其结构如下:
string s = "0R 0R 20.0V 100.0V 400.0R 60R 70.0R";
我的问题是,我如何通过这样的 if 语句仅检测 3rd、4th、5th 字母:
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 循环来遍历字符串,但我不确定如何检测它何时是 3rd、4th、5th 字母,我知道 regex em> 可能会有所帮助,但我不确定如何实现表达式
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
}
【问题讨论】:
-
string[] letters = Regex.Matches(s, "[A-Z]").Cast<Match>().Select(m => m.Value).ToArray(); -
只有我们索引操作符。
s[0]是第 0 个字符,s[1]是第一个字符,s[2]是第二个字符,以此类推 -
“检测第三个字母”到底是什么意思?你的意思是,忽略不属于字母的任何内容,我想要字符串中的第三个字符?
-
所以在字符串中:
0R 0R 20.0V...我想检测第三个字母,在这种情况下是 V -
试试上面@DmitryBychenko 的例子。然后使用
letters[2]获取第三个字母。
标签: c# string parsing detection