This topic contains 6 replies, has 5 voices, and was last updated by
August 29, 2013 at 7:27 am #9835ParticipantTopics: 1Replies: 1Points: 0Rank: Member
What would be the best way to handle this?
If I wanted to insert leading characters based on a length defined by a number. I would like to use in a PowerShell Script where I can do $value.length then subtract that from a predefined number. The difference would then define how many Aâ€™s are inserted at the start of the string.
$field = "10"
$value = â€œFARMâ€
$value.lengnth returns 4
$field - $value.length is 6.
Create new string of AAAAAAFARM
August 29, 2013 at 7:39 am #9836ParticipantTopics: 0Replies: 6Points: 0Rank: Member
$value = $value.PadLeft($field,"A")
August 29, 2013 at 7:41 am #9837KeymasterTopics: 13Replies: 4872Points: 1,811Rank: Community Hero
Strings have an Insert() method. Insert(2,"x") would insert "x" at the 2nd position. You could also use the PadLeft() or PadRight() methods, which accept a desired string length and the length you'd like the string padded to. So, if you wanted a string of 10 characters, $string.PadLeft(10,'A') would insert on the left however many A's were needed to make it 10 characters.
August 29, 2013 at 9:14 am #9838ParticipantTopics: 1Replies: 1Points: 0Rank: Member
PadLeft() is perfect for what I need. Thank you both.
August 29, 2013 at 1:35 pm #9845ParticipantTopics: 8Replies: 1190Points: 639Rank: Major Contributor
I hadn't used these methods before and was playing around with it. It doesn't appear to work with spaces. Thoughts?
PS C:\Windows\system32> $test = "TEST" PS C:\Windows\system32> $test.PadLeft(10, "A") AAAAAATEST PS C:\Windows\system32> $test = "This is a test" PS C:\Windows\system32> $test.PadLeft(10, "A") This is a test
August 29, 2013 at 1:43 pm #9848MemberTopics: 9Replies: 2322Points: 0Rank: Member
I'm not sure what output you're expecting to see, Rob. "This is a test" is longer than 10 characters, so the PadLeft method will just return the original string. If you increased the first argument to something longer than the string, it would start adding "A" characters.
August 29, 2013 at 2:03 pm #9850ParticipantTopics: 8Replies: 1190Points: 639Rank: Major Contributor
Ahhh, I get it now. I was thinking it was going to be 10 A's appended to the front the string versus adding A's for a total length of 10. Though the lightbulb may be dim, it's on now. 🙂 Thanks Dave. Appreciate all your responses, I'm just reading and absorbing want I can.
The topic ‘Add Char to string based on number.’ is closed to new replies.