计算空格数,并在最后一个分割 [英] Count number of spaces, and split at the last one
问题描述
我有一个字符串simliar:
I have a string simliar to:
c:/folder name/somewhere/application.exe instanceName
(文件夹名称中的空格是有意的)我需要一种方法将它分成:
(n.b. the space in "folder name" is intentional) I need a way to split this into:
[0]c:/folder name/somewhere/application.exe
[1]instanceName
我将使用 split-path
,但显然有一个错误powershell v2阻止我这样做:
I was going to use split-path
, but apparently there is a bug in powershell v2 that stops me doing this:
Split-Path : Cannot find drive. A drive with the name '
所以,我想如果我计算有多少空格,然后只需使用 -split()
将其分割到最后一个空格。
但是,我看不到如何计算空格数。
我发现了很多关于使用regex来计算复杂字符串的例子,但我只想计算空格。
So, I figured if I count how many spaces there are, and then simply use -split()
to split it at the last space.
But, I can't see how to count the number of spaces.
I've found lots of examples that talk about using regex to count complex strings, but I just want to count spaces!
推荐答案
实现这一目标的方法我想象,但使用你的分裂的想法,你可以做以下。
Tonnes of ways to do this I imagine but to use your split idea you could do the following.
$split = "c:/folder name/somewhere/application.exe instanceName".Split(" ")
$path = $split[0..($split.count -2)] -Join " "
$instance = $split[-1]
用空格分割sting。空格数由数组 $ split
中的字符串数表示。我们加入数组中的所有字符串接受最后一个int $ path
,然后我们取最后一个条目并将其分配给 $ instance
Split the sting by spaces. The number of spaces is represented by the count of strings in the array $split
. We join all the strings in the array accept the last intp $path
then we take the last entry and assign it to $instance
您也可以使用 .substring
和 .lastindexof
$string = "c:/folder name/somewhere/application.exe instanceName"
$index = $string.LastIndexOf(" ")
$string.Substring(0,$index)
$string.Substring($index + 1)
我看不到这种方式直接分割成一个数组在这个时候,但输出作为一个数组不会是一个大事。
I can't see a way to split this directly into an array at this time but outputing as an array would not be a big deal.
$path, $instance
或
$array = @($path,$instance)
这篇关于计算空格数,并在最后一个分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!