Grady D
Grady D

Reputation: 2019

Remove last character in dynamic string

I am having issues with removing the last character of a dynamically populated string. The last character is a ',' and I can remove it but the problem is that when I print out the list the comma is still there. To create the string I read information in from a CSV into an array. I then take everything in the array and convert it to the final format.

for ($i = 0; $i -lt $CSVArray.Length; $i++) {
  $longString = $longString + "'" + $CSVArray[$i] + "',"
}

Then I find the length of the string,

$length = $longString.Length

Finally I remove the last character,

$longString = $longString.Substring($length - 1).Replace(",", "")

When I output $longString.Substring($length - 1) I get just the comma but when I output $longString after doing the replace it still has the comma at the end.

How can I remove the very last character from longString?

Upvotes: 3

Views: 7583

Answers (3)

Gama_Days
Gama_Days

Reputation: 11

Deletes the last Charakter:

$LongString = $LongString ".$"

Deletes the 2 last Charakters:

$LongString = $LongString "..$"

As so on!

Upvotes: 0

DarkAjax
DarkAjax

Reputation: 16223

As @Ansgar Wiechers mentions, using -join in your case is better. For other strings/cases this would work:

$longString = $longString.Substring(0,$longString.Length -1);

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Simply -join the array:

$longString = "'" + ($CSVArray -join "','") + "'"

Upvotes: 4

Related Questions