本帖最后由 nwm310 于 2020-10-11 11:11 编辑
注意事项:
-eq 不区分大小写。如果有需要,请改用 -ceq
PS C:\> 'a' -eq 'A'
True
PS C:\> 'a' -ceq 'A'
False
|
在 $Text 里面找 $Key ( 1个字 )
$Text = 'ABAQABAB'
$Key = 'B'
for ( $base = 0 ; $base -lt $Text.Length ; $base++ ){
if ( $Key -eq $Text[$base] ){ break }
}
if ($base -eq $Text.Length){
'没找到'
}else{
"$Key 在 $base"
}
|
在 $Text 里面找 $Key ( 2个字 or 2个字以上)
$Text = 'ABAQABAB'
$Key = 'ABAB'
$baseEnd = $Text.Length - ($Key.Length - 1)
for ( $base = 0 ; $base -lt $baseEnd ; $base++ ){
for ($j = 0 ; $j -lt $Key.Length ; $j++){
if ( $Key[$j] -ne $Text[$base + $j] ){ break }
}
if ($j -eq $Key.Length){ break }
}
if ($base -eq $baseEnd){
'没找到'
}else{
"$Key 在 $base"
}
|
把 第一层 for 改成 while
$Text = 'ABAQABAB'
$Key = 'ABAB'
$base = 0 # edit 1
$baseEnd = $Text.Length - ($Key.Length - 1)
while ($base -lt $baseEnd){ # edit 2
for ($j = 0 ; $j -lt $Key.Length ; $j++){
if ( $Key[$j] -ne $Text[$base + $j] ){ break }
}
if ($j -eq $Key.Length){ break }
$base += 1 # edit 3
}
if ($base -eq $baseEnd){
'没找到'
}else{
"$Key 在 $base"
}
|
|