string.f90 1.67 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
module m_juDFT_string
   implicit none
   character(len=3), parameter :: whitespaces = " " // achar(9) // achar(13) ! list of all whitespaces
contains
   function strip(input) result(output)
      implicit none
      character(len=*), intent(in)  :: input
      character(:), allocatable     :: output

      integer                       :: front, back

      front = 1
      do while(index(whitespaces, input(front:front)) /= 0 )
         front = front + 1
      enddo

      back  = len(input)
      do while(index(whitespaces, input(back:back)) /= 0)
         back = back - 1
      enddo

      output = input(front:back)
   end function strip
Matthias Redies's avatar
Matthias Redies committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

   function str2int(str) result(int)
      implicit none
      character(len=*), intent(in) :: str
      integer                      :: int
      integer                      :: stat

      read (str, *, iostat=stat) int
      if (stat /= 0) then
         write (*, *) "str reading failed", str
         stop 9
      endif
   end function str2int

   function int2str(num) result(ret_str)
      implicit none
      integer, intent(in)            :: num
      character(len=:), allocatable  :: ret_str

      allocate(character(100) :: ret_str)
      write (ret_str,*) num
      ret_str = strip(ret_str)
   end function int2str
Matthias Redies's avatar
Matthias Redies committed
47 48 49 50 51 52 53 54 55 56
   
   function float2str(num) result(ret_str)
      implicit none
      real, intent(in)               :: num
      character(len=:), allocatable  :: ret_str

      allocate(character(100) :: ret_str)
      if(num >= 1e-1 .and. num <= 1e4) then
         write (ret_str,"(F10.5)") num
      else
Matthias Redies's avatar
Matthias Redies committed
57
         write (ret_str,"(ES12.4)") num
Matthias Redies's avatar
Matthias Redies committed
58 59 60
      endif
      ret_str = strip(ret_str)
   end function float2str
61
end module m_juDFT_string