Как определить 3-ю, 4-ю, 5-ю букву в строке C# - PullRequest
0 голосов
/ 03 августа 2020

У меня string структурирован как:

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

Мой вопрос в том, как мне обнаружить только 3-й , 4-й , 5-я буква через операторы 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 от l oop до l oop через строку, но я не уверен, как определить, когда это 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
}

1 Ответ

2 голосов
/ 03 августа 2020

Сначала давайте извлечем / сопоставим буквы либо с помощью 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];
...