查找字符串中任何一个数组元素的第一次出现 - Powershell

Find first occurrence of any one of the array elements in a string - Powershell

问题是找到数组中任何元素第一次出现的位置。

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

$StringToBeSearched = "ABC$DEFG#";

预期输出需要为:3,因为“$”出现在 $StringToBeSearched 变量中的任何其他 $term 之前

此外,我们的想法是以成本最低的方式进行。

# 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