s2c Function

public pure function s2c(string) result(array)

NAME

  s2c(3f) - [M_strings:ARRAY] convert character variable to array of
  characters with last element set to null
  (LICENSE:PD)

SYNOPSIS

function s2c(string)

 character(len=*),intent=(in)  :: string
 character(len=1),allocatable  :: s2c(:)

DESCRIPTION

Given a character variable convert it to an array of single-character
character variables with the last element set to a null character.
This is generally used to pass character variables to C procedures.

EXAMPLES

Sample Program:

 program demo_s2c
 use M_strings, only : s2c
 implicit none
 character(len=*),parameter   :: string="single string"
 character(len=3),allocatable :: array(:)
    write(*,*)'INPUT STRING ',trim(string)
    ! put one character into each 3-character element of array
    array=s2c(string)
    ! write array with ASCII Decimal Equivalent below it except show
    ! unprintable characters like NULL as "XXX"
    write(*,'(1x,*("[",a3,"]":))')&
         & merge('XXX',array,iachar(array(:)(1:1)) < 32)
    write(*,'(1x,*("[",i3,"]":))')&
         & iachar(array(:)(1:1))
 end program demo_s2c

Expected output:

INPUT STRING single string
[s  ][i  ][n  ][g  ][l  ][e  ][   ][s  ][t  ][r  ][i  ][n  ][g  ][XXX]
[115][105][110][103][108][101][ 32][115][116][114][105][110][103][  0]

AUTHOR

John S. Urban

LICENSE

Public Domain

Arguments

Type IntentOptional Attributes Name
character(len=*), intent(in) :: string

Return Value character(kind=C_CHAR, len=1), (len_trim(string)+1)


Contents

Source Code

s2c

Source Code

pure function s2c(string)  RESULT (array)
use,intrinsic :: ISO_C_BINDING, only : C_CHAR

! ident_27="@(#) M_strings s2c(3f) copy string(1 Clen(string)) to char array with null terminator"

character(len=*),intent(in)     :: string

! This is changing, but currently the most portable way to pass a CHARACTER variable to C is to convert it to an array of
! character variables with length one and add a null character to the end of the array. The s2c(3f) function helps do this.
character(kind=C_CHAR,len=1)    :: array(len_trim(string)+1)
integer                         :: i
   do i = 1,size(array)-1
      array(i) = string(i:i)
   enddo
   array(size(array):)=achar(0)
end function s2c