[英]Replacing Part of String at Position in Powershell
Right now i'm trying to convert my C#
Code to an PowerShell
Script. 现在,我正在尝试将C#
代码转换为PowerShell
脚本。
My actual function in C#
looks like this: 我在C#
实际功能如下所示:
private static string ReplaceStringPartAt(string mainstring, int position, string replacement)
{
StringBuilder strBuilder = new StringBuilder(mainstring);
strBuilder.Remove(position, replacement.Length);
strBuilder.Insert(position, replacement);
return strBuilder.ToString();
}
And my PowerShell
function like this: 我的PowerShell
函数如下所示:
function ReplaceStringPartAt($mainstring, $position, $replacement)
{
$strBuilder = New-Object System.Text.StringBuilder;
$strBuilder.AppendLine($mainstring)
$strBuilder.Remove($position, $replacement.Length);
$strBuilder.Insert($position, $replacement);
return $strBuilder.ToString();
}
But i alway get an [System.Text.StringBuilder]
as return value. 但是我总是得到一个[System.Text.StringBuilder]
作为返回值。
What do i miss to make the function work again? 我想让该功能再次起作用是什么?
Many of the methods of the StringBuilder
class return the same StringBuilder
instance so you can chain multiple calls together. StringBuilder
类的许多方法都返回相同的StringBuilder
实例,因此您可以将多个调用链接在一起。 This is harmless in C#, but in PowerShell you need to explicitly capture these return values so they don't appear in your function output. 在C#中这是无害的,但是在PowerShell中,您需要显式捕获这些返回值,以便它们不会出现在函数输出中。 You can either pipe them to Out-Null
... 您可以将它们通过管道传输到Out-Null
...
$strBuilder.AppendLine($mainstring) | Out-Null
$strBuilder.Remove($position, $replacement.Length) | Out-Null;
$strBuilder.Insert($position, $replacement) | Out-Null;
...or cast them to [Void]
... ...或将其投放到[Void]
...
[Void] $strBuilder.AppendLine($mainstring)
[Void] $strBuilder.Remove($position, $replacement.Length);
[Void] $strBuilder.Insert($position, $replacement);
...or chain all of the calls (including .ToString()
) together... ...或将所有调用(包括.ToString()
)链接在一起...
return $strBuilder.AppendLine($mainstring) `
.Remove($position, $replacement.Length) `
.Insert($position, $replacement) `
.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.