【问题标题】:How to detect the 3rd, 4th, 5th letter in a string C#如何检测字符串C#中的第3、4、5个字母
【发布时间】:2020-08-03 20:27:36
【问题描述】:

我有一个string,其结构如下:

string s = "0R   0R  20.0V  100.0V  400.0R    60R  70.0R";

我的问题是,我如何通过这样的 if 语句仅检测 3rd4th5th 字母:

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


【解决方案1】:

首先,让我们在 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];

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2019-08-05
    • 2013-10-29
    • 1970-01-01
    相关资源
    最近更新 更多