string 将字符串拆分为单独的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30617758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:23:21  来源:igfitidea点击:

Splitting a string into separate variables

stringpowershell

提问by davetherave

I have a string, which I have split using the code $CreateDT.Split(" "). I now want to manipulate two separate strings in different ways. How can I separate these into two variables?

我有一个字符串,我使用代码拆分了它$CreateDT.Split(" ")。我现在想以不同的方式操作两个单独的字符串。我怎样才能将这些分成两个变量?

回答by mjolinor

Like this?

像这样?

$string = 'FirstPart SecondPart'
$a,$b = $string.split(' ')
$a
$b

回答by vonPryz

An array is created with the -splitoperator. Like so,

使用-split运算符创建数组。像这样,

$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output
Four
score
and
seven
years
ago

When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,

当您需要某个项目时,请使用数组索引来访问它。请注意索引从零开始。像这样,

$arr[2] # 3rd element
and
$arr[4] # 5th element
years

回答by 0xG

It is important to note the following difference between the two techniques:

重要的是要注意这两种技术之间的以下区别:

$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT 

From this you can see that the string.split()method:

从中可以看出该string.split()方法

  • performs a case sensitivesplit (note that "ALL RIGHT" his split on the "R" but "broken" is not split on the "r")
  • treats the string as a list of possible characters to split on
  • 执行区分大小写的拆分(请注意,“ALL RIGHT”他在“R”上的拆分​​但“broken”不会在“r”上拆分)
  • 将字符串视为要拆分的可能字符列表

While the -splitoperator:

-split运营商

  • performs a case-insensitive comparison
  • only splits on the whole string
  • 执行不区分大小写的比较
  • 只在整个字符串上拆分

回答by Esperento57

Try this:

尝试这个:

$Object = 'FirstPart SecondPart' | ConvertFrom-String -PropertyNames Val1, Val2
$Object.Val1
$Object.Val2

回答by js2010

Foreach-object operation statement:

Foreach-object操作语句:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there