Silverfrost Forums

Welcome to our forums

Converting string into array of characters

15 May 2023 10:19 #30310

How can I

  1. convert a string into array of characters?
  2. convert an array of characters into a string? Patrick.
15 May 2023 11:11 #30311
implicit none
integer i, n
character(len=26) :: a2z, z2a
character(len=1)  :: ch(26)
n   = 26
a2z = ''
print'(A)', a2z
do i = 97, 97+n, 1
  a2z = trim(a2z)//char(i)
end do
print'(A)', a2z    ! Initial string
do i = 1, n
  ch(i) = a2z(i:i) ! Character array
end do
z2a = ''
print'(A)', z2a
do i = n, 1, -1    !Reverse order
  z2a = trim(z2a)//ch(i)
end do
print'(A)', z2a   ! New string formed from character array
end



abcdefghijklmnopqrstuvwxyz

zyxwvutsrqponmlkjihgfedcba
15 May 2023 4:20 #30313

Expanding to use subroutines 'String2array' and 'Array2string':

implicit none
integer i, n
character(len=128) :: a2z, a2zcopy
character(len=1), allocatable  :: array(:)

interface

  subroutine string2array(str,array)
    character(len=*), intent(in) :: str
    character(len=1), allocatable, intent(out) :: array(:)
  end subroutine string2array

  subroutine array2string(array,str)
    character(len=1), allocatable, intent(in) :: array(:)
    character(len=*), intent(out) :: str
  end subroutine
  
end interface

n   = 26
a2z = ''
print'(A)', trim(a2z)
do i = 97,97+n-1
  a2z = trim(a2z)//char(i)
end do

print'(25A,5X,A)', 'Initial string:          ',trim(a2z)

call string2array(a2z,array)

a2zcopy = ''
print'(A)', trim(a2zcopy)

call array2string(array,a2zcopy)
print'(25A,5X,A)', 'String from char array:  ',trim(a2zcopy)
end

  subroutine string2array(str,array)
  character(len=*), intent(in) :: str
  character(len=1), allocatable, intent(out) :: array(:)
  integer i, n
  if (allocated(array)) deallocate(array)
    n = len_trim(str)
    allocate(array(n))
    forall (i=1:n) array(i) = str(i:i)
  end subroutine string2array

  subroutine array2string(array,str)
  character(len=1), allocatable, intent(in) :: array(:)
  character(len=*), intent(out) :: str
  integer i, n
  if (.not. allocated(array)) STOP 'Error'
    str = ''
    do i = 1, size(array), 1
      str = trim(str)//array(i)
    end do
  end subroutine array2string 
16 May 2023 9:54 #30318

Thank you very much for the code with which you responded to my query! Patrick.

Please login to reply.