Using PowerShell to find the differences in strings

前端 未结 1 1428
我寻月下人不归
我寻月下人不归 2021-01-15 04:58

So I\'m playing around with Compare-Object, and it works fine for comparing files. But what about just strings? Is there a way to find the difference between strings? Compar

1条回答
  •  囚心锁ツ
    2021-01-15 05:06

    Perhaps something like this:

    function Compare-String {
      param(
        [String] $string1,
        [String] $string2
      )
      if ( $string1 -ceq $string2 ) {
        return -1
      }
      for ( $i = 0; $i -lt $string1.Length; $i++ ) {
        if ( $string1[$i] -cne $string2[$i] ) {
          return $i
        }
      }
      return $string1.Length
    }
    

    The function returns -1 if the two strings are equal or the position of the first difference between the two strings. If you want case-insensitive comparisons, you would need to use -eq instead of -ceq and -ne instead of -cne.

    0 讨论(0)
提交回复
热议问题