Add Char to string based on number.

This topic contains 6 replies, has 5 voices, and was last updated by Profile photo of Rob Simmers Rob Simmers 3 years, 10 months ago.

  • Author
  • #9835
    Profile photo of Robert Skinner
    Robert Skinner

    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

  • #9836
    Profile photo of Bob McCoy
    Bob McCoy

    $value = $value.PadLeft($field,"A")

  • #9837
    Profile photo of Don Jones
    Don Jones

    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.

  • #9838
    Profile photo of Robert Skinner
    Robert Skinner

    PadLeft() is perfect for what I need. Thank you both.

  • #9845
    Profile photo of Rob Simmers
    Rob Simmers

    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")
    PS C:\Windows\system32> $test = "This is a test"
    PS C:\Windows\system32> $test.PadLeft(10, "A")
    This is a test
  • #9848
    Profile photo of Dave Wyatt
    Dave Wyatt

    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.

  • #9850
    Profile photo of Rob Simmers
    Rob Simmers

    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.

You must be logged in to reply to this topic.