当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在 PowerShell 中用下划线替换空格

作者:精品下载站 日期:2024-12-14 05:23:18 浏览:12 分类:玩电脑

在 PowerShell 中用下划线替换空格


? TL;DR 要在 PowerShell 中用下划线替换空格,请使用 String 的 Replace() 方法或 PowerShell 的替换运算符。

这是一个简单的例子:

将字符串中的空格替换为下划线:

$countries= "India China Bhutan Russia"
$countriesWithUnderscore = $countries.Replace(" ","_")
$countriesWithUnderscore

#Output : India_China_Bhutan_Russia

在 PowerShell 中,有多种方法可以用下划线替换空格。让我们来看看它们。

使用String的replace()方法

您可以使用字符串的replace()方法在PowerShell中用下划线替换空格。

Replace 方法返回新字符串并用新文本替换每个匹配的文本。
Replace 方法采用两个参数:

  • 在给定字符串中查找的子字符串:空格
  • 找到的字符串的替换字符串:下划线

将字符串中的空格替换为下划线:

$countries= "India China Bhutan Russia"
$countriesWithUnderscore = $countries.Replace(" ","_")
$countriesWithUnderscore

#Output : India_China_Bhutan_Russia

使用替换运算符

您可以使用PowerShell的替换运算符在PowerShell中用下划线替换空格。

替换运算符有两个参数:

  • 在给定字符串中查找的子字符串:空格
  • 找到的字符串的替换字符串:下划线

将字符串中的空格替换为下划线:

$countries= "India China Bhutan Russia"
$countriesWithUnderscoreOpr =  $countries -replace " ","_"
$countriesWithUnderscoreOpr

#Output : India_China_Bhutan_Russia

如您所见,替换运算符替换了字符串中所有带有下划线的空格。

请注意,我们已将replace()方法或replace()运算符的结果分配给新字符串,

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯