Add Char to string based on number.

Welcome Forums General PowerShell Q&A Add Char to string based on number.

This topic contains 6 replies, has 5 voices, and was last updated by

 
Participant
5 years, 3 months ago.

  • Author
    Posts
  • #9835

    Participant
    Points: 0
    Rank: 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

  • #9836

    Participant
    Points: 0
    Rank: Member

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

  • #9837

    Keymaster
    Points: 1,704
    Helping HandTeam Member
    Rank: 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.

  • #9838

    Participant
    Points: 0
    Rank: Member

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

  • #9845

    Participant
    Points: 324
    Helping Hand
    Rank: 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
    
  • #9848

    Member
    Points: 0
    Rank: 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.

  • #9850

    Participant
    Points: 324
    Helping Hand
    Rank: 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.