rimraf
rimraf

Reputation: 4126

Exploding a random string

How would one "explode" a random string? What I'm after is; taking a random string of n length

characters=$(</dev/urandom tr -dc '1234567890{}[]`~\/><!@#$%^&*()_+=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | head -c${n})

exploding the characters such that they fit within k space

k=27

a r a n d 0 M B u n c H 0 f

where k is the "exploded" legnth.

Ultimately I would like to set a carrot "^" under each of the characters and have it follow along what is typed.

see my other post here

Upvotes: 1

Views: 83

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84521

You can use the integer math capability provided by bash to calculate the number of spaces will fit between each character to expand the string to a maximum requested size of k (only equal number of spaces between each char and noting there are n-1 slots between n chars to expand)

You simply calculate the length of the string, you have the requested size you want to expand to, using integer division (with intentional truncation) you can compute the number of spaces you can put between each char while staying within the requested size. You can do that with something like the following:

#!/bin/bash

str="string to explode" ## string
len=${#str}             ## string length
k=$((${1:-70}))         ## exploded size requested

((k < len)) && {    ## validate requested size > length
    printf "error: width 'k' less than length '%d'\n" "$len"
    exit 1
}

sep=$((k/len))  ## max separation between chars (integer division)

((sep < 2)) && {    ## if 1, cannot explode 
    printf "%s (no expansion)\n" "$str"
    exit 0
}

sepst=""    ## set separator string
printf -v sepst "%*s" $((sep - 1)) " "

## insert sepst betwen each char
for ((i = 0; i < $((len - 1)); i++)); do
    printf "%s%s" ${str:$((i)):1} "$sepst"  ## str intentionally unquoted
done                                        ## (quote for preserve space)

## print final char
printf "%s\n" "${str: -1}"

Which takes "string to explode" and expands to a requested size of 70 (computing that an even max separation is 3-spaces between each character for a total (17 + 48 = 65 chars)

Example Use

$ explodestr.sh
s   t   r   i   n   g      t   o      e   x   p   l   o   d   e

To print each space with separators on either side, quote "${str:$((i)):1}" which will preserve (instead of omitting) each space. (take your pick -- it just makes the spaces more pronounced)

$ explodestr.sh
s   t   r   i   n   g       t   o       e   x   p   l   o   d   e

Upvotes: 1

Related Questions