【问题标题】:Create an array from a string in PowerShell在 PowerShell 中从字符串创建数组
【发布时间】:2012-11-26 17:27:28
【问题描述】:

如何从包含字符串“3 4 5 4 3”的变量创建整数数组?

【问题讨论】:

  • 您尝试过什么,以及在哪些方面没有奏效?请不要在没有亲自尝试的情况下要求答案。

标签: arrays string powershell integer


【解决方案1】:

拆分字符串创建一个字符串数组,添加一个强制转换到一个整数数组:

[int[]]"3 4 5 4 3".Split()

【讨论】:

    【解决方案2】:

    我更喜欢:

    [int[]] -split "3 4 5  4   3"
    

    -splitString.Split() 更好地处理空白空间。使用String.Split(),如果数字之间有多个空格,则生成的数组中会出现空字符串。 PowerShell 将空字符串强制为 0,例如:

    C:\PS> [int[]]"3 4 5  4   3".Split()
    3
    4
    5
    0
    4
    0
    0
    3
    

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      相关资源
      最近更新 更多