Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 974
Grady D Avatar asked Nov 22 '25 12:11

Grady D


2 Answers

Simply -join the array:

$longString = "'" + ($CSVArray -join "','") + "'"
like image 171
Ansgar Wiechers Avatar answered Nov 24 '25 04:11

Ansgar Wiechers


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);
like image 38
DarkAjax Avatar answered Nov 24 '25 04:11

DarkAjax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!