使用PowerShell查找字符串中的差异 [英] Using PowerShell to find the differences in strings

查看:206
本文介绍了使用PowerShell查找字符串中的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用Compare-Object,它可以很好地比较文件.但是,仅仅是字符串呢?有没有办法找到字符串之间的区别? CompareTo()可以很好地报告存在差异,但是没有区别.例如:

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:>

一无所有.

有什么方法可以让我知道字符串之间的实际差异,而不仅仅是存在差异?

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

推荐答案

也许是这样的:

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
}

如果两个字符串相等或两个字符串之间的第一个差的位置,则该函数返回-1.如果要进行不区分大小写的比较,则需要使用-eq代替-ceq,并使用-ne代替-cne.

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.

这篇关于使用PowerShell查找字符串中的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆