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?
Simply -join the array:
$longString = "'" + ($CSVArray -join "','") + "'"
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With