Найти первое вхождение любого из элементов массива в строке - Powershell - PullRequest
1 голос
/ 25 марта 2020

Проблема состоит в том, чтобы найти позицию самого первого вхождения любого из элементов массива.

$terms = @("#", ";", "$", "|");

$StringToBeSearched = "ABC$DEFG#";

Ожидаемый результат должен быть: 3, так как '$' встречается до того, как любой из другие $ термины в переменной $ StringToBeSearched

Кроме того, идея состоит в том, чтобы сделать это наименее дорогим способом.

1 Ответ

4 голосов
/ 25 марта 2020
# Define the characters to search for as an array of [char] instances ([char[]])
# Note the absence of `@(...)`, which is never needed for array literals,
# and the absence of `;`, which is only needed to place *multiple* statements
# on the same line.
[char[]] $terms = '#', ';', '$', '|'

# The string to search trough.
# Note the use of '...' rather than "...", 
# to avoid unintended expansion of "$"-prefixed tokens as
# variable references.
$StringToBeSearched = 'ABC$DEFG#'

# Use the [string] type's .IndexOfAny() method to find the first 
# occurrence of any of the characters in the `$terms` array.
$StringToBeSearched.IndexOfAny($terms)  # -> 3
...