Using PowerShell to find the differences in strings

点点圈 提交于 2019-12-19 10:59:17

问题


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? CompareTo() is good about reporting that there is a difference, but not what the difference is. For example:

PS:> $a = "PowerShell rocks"
PS:> $b = "Powershell rocks"
PS:> $a.CompareTo($b)
1
PS:> Compare-Object -ReferenceObject $a -DifferenceObject $b
PS:>

Nothing returned.

Any way to let me know about the actual difference between the strings, not just that there is a difference?


回答1:


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.



来源:https://stackoverflow.com/questions/25169424/using-powershell-to-find-the-differences-in-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!