0

How do we convert a string into N character array and back to string with spaces? And how do we remove the spaces?

e.g. 123456789 into 2's should give 12 34 56 78 9

4 Answers 4

3

Sounds like you don't need the array at all and your final goal is just to insert spaces between groups of two characters. If that's the case you can use

 sed 's/../& /g' <<< "your string here"

This will transform your example input 123456789 into the expected output 12 34 56 78 9.

Of course you can assign the result to a variable as usual:

yourVariable="$(sed 's/../& /g' <<< "your string here")"

if needed, how do we remove the spaces?

I'm not sure which spaces you mean. If you are talking about the final result, wouldn't it be easier to use the original input instead of procession the ouput again?
Anyways, you can remove all spaces from a any string using tr -d ' ' <<< "your string" or the parameter substitution ${yourVariable// /}.

Sign up to request clarification or add additional context in comments.

Comments

3
$ str='123456789'

$ arr=( $(printf '%s\n' "$str" | sed 's/../& /g') )
$ declare -p arr
declare -a arr=([0]="12" [1]="34" [2]="56" [3]="78" [4]="9")

$ str="${arr[*]}"
$ echo "$str"
12 34 56 78 9

$ str="${str// }"
$ echo "$str"
123456789

$ str=$(printf "%s" "${arr[@]}")
$ echo "$str"
123456789

Comments

2
  1. If you need to split a string into array, you can use IFS variable:
IFS=' '
arr=( )
read -r -a arr <<< "string morestring another"
unset IFS
  1. To remove spaces from string you can use different approaches, one of them is:
str="123 123  12312312"
echo ${str// /}
//output: 12312312312312

Comments

0

This would be demonstrative to your question.

Convert a string into N character array:

string="0123456789abcdefghijklmnopqrstuvwxyz"
number_max_of_char_per_set=4
increment_by=$number_max_of_char_per_set

for i in `seq 0 $increment_by ${#string}`
#for i in $(seq 0 ${#string})
    do array[$i]=${string:$i:number_max_of_char_per_set}
done

... back to string with spaces:

string_new=${array[@]}

echo "zero element of array is [${array[0]}]"
echo "entire array is [${array[@]}]"
echo $string_new

remove the spaces:

string_new=${string_new//[[:space:]]/}
echo $string_new

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.