简体   繁体   中英

How do I remove a trailing comma from a string

I have a string producing results in PowerShell being separated by a comma, which is fine, but I don't want the last comma.

I understand a Trim function is required, but I can't seem to get it to work. Maybe i've been trying it in the wrong place?

I need it to return three "Site Codes, each separated with a comma, and no comma at the end. I need to know where to add the trim bit really.

$UKPRN = "10007405"
$str_sites = "A4EYORK,AVLEEDS,BANBURY";

$sites = "";


foreach ($site in $str_sites.Split(","))
{
$sites = $sites+"'"+$site+"',"

}
Write-Output $sites;

You could just use TrimEnd()

$str = "string with , at the end,"
$str.TrimEnd(",")

Your string building method is what is creating that issue for you in the first place. You want to quote all elements of your string correct? Quote your array elements individually then use -join and there will be no artifacts that you have to deal with.

$sites = "A4EYORK,AVLEEDS,BANBURY"
($sites.split(",") | ForEach-Object{"'$_'"}) -join ","
$str_sites = "A4EYORK,AVLEEDS,BANBURY"

$sites = $str_sites.Split(",") | % { "'{0}'" -f $_ }

Write-Output ($sites -join ',')

$sites is array, joined with ',' by using -join operator. For more information about -join , see the Microsoft Docs

我个人使用String.Split()String.Join() ,但是由于您的所有术语都是由文字字符组成的,因此您也可以使用简单的正则表达式替换模式轻松地做到这一点:

$str_sites = $str_sites -replace '\b(\w+)\b',"'`$1'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM