Tokenize a string in order to parse it.
The dummy array containing tokens must be allocatable and its character elements must have the same length of the input string. If the length of the delimiter is higher than the input string one then the output tokens array is allocated with only one element set to char(0).
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
character(len=*), | intent(in) | :: | string | String to be tokenized. |
||
character(len=*), | intent(in) | :: | delimiter | Delimiter of tokens. |
||
character(len=len(string)), | intent(out), | allocatable | :: | toks(:) | Tokens. |
|
integer(kind=I_P), | intent(out), | optional | :: | Nt | Number of tokens. |
Nodes of different colours represent the following:
Solid arrows point from a procedure to one which it calls. Dashed arrows point from an interface to procedures which implement that interface. This could include the module procedures in a generic interface or the implementation in a submodule of an interface in a parent module.
pure subroutine tokenize(string, delimiter, toks, Nt)
!< Tokenize a string in order to parse it.
!<
!< @note The dummy array containing tokens must be allocatable and its character elements must have the same length of the input
!< string. If the length of the delimiter is higher than the input string one then the output tokens array is allocated with
!< only one element set to char(0).
character(len=*), intent(IN) :: string !< String to be tokenized.
character(len=*), intent(IN) :: delimiter !< Delimiter of tokens.
character(len=len(string)), allocatable, intent(OUT) :: toks(:) !< Tokens.
integer(I_P), optional, intent(OUT) :: Nt !< Number of tokens.
character(len=len(string)) :: strsub !< Temporary string.
integer(I_P) :: dlen !< Delimiter length.
integer(I_P) :: c !< Counter.
integer(I_P) :: n !< Counter.
integer(I_P) :: t !< Counter.
! initialize
if (allocated(toks)) deallocate(toks)
strsub = string
dlen = len(delimiter)
if (dlen>len(string)) then
allocate(toks(1:1))
toks(1) = char(0)
if (present(Nt)) Nt = 1
return
endif
! compute the number of tokens
n = 1
do c=1, len(strsub) - dlen ! loop over string characters
if (strsub(c:c+dlen-1)==delimiter) n = n + 1
enddo
allocate(toks(1:n))
! tokenize
do t=1, n ! loop over tokens
c = index(strsub, delimiter)
if (c>0) then
toks(t) = strsub(1:c-1)
strsub = strsub(c+dlen:)
else
toks(t) = strsub
endif
enddo
if (present(Nt)) Nt = n
endsubroutine tokenize