@@ -16,6 +16,7 @@ module string_module
1616 public :: replace_char
1717 public :: reverse
1818 public :: lchop, rchop
19+ public :: strip
1920
2021 contains
2122! *****************************************************************************************
@@ -152,6 +153,60 @@ pure function reverse(str) result(newstr)
152153 end function reverse
153154! *****************************************************************************************
154155
156+ ! *****************************************************************************************
157+ ! >
158+ ! Strip all occurances of chars from the beginning and end of the string.
159+
160+ pure function strip (str , chars ) result(newstr)
161+
162+ character (len=* ),intent (in ) :: str ! ! original string
163+ character (len=* ),intent (in ),optional :: chars ! ! characters to strip
164+ character (len= :),allocatable :: newstr ! ! new string
165+
166+ integer :: i ! ! counter
167+ integer :: n ! ! length of str
168+ integer :: idx ! ! for using scan
169+ integer :: start_idx, end_idx ! ! substring to keep
170+
171+ if (present (chars)) then
172+ if (chars /= ' ' ) then
173+ ! have to step through manually from beginning and end
174+ n = len (str)
175+ start_idx = 1
176+ end_idx = n
177+ ! forward search
178+ do i = 1 , n
179+ idx = scan (str(i:i), chars)
180+ if (idx > 0 ) then
181+ start_idx = start_idx + 1
182+ else
183+ exit
184+ end if
185+ end do
186+ ! backward search
187+ do i = n, 1 , - 1
188+ idx = scan (str(i:i), chars)
189+ if (idx > 0 ) then
190+ end_idx = end_idx - 1
191+ else
192+ exit
193+ end if
194+ end do
195+ if (end_idx <= start_idx) then
196+ newstr = ' ' ! all stripped
197+ else
198+ newstr = str(start_idx:end_idx) ! return substring
199+ end if
200+ return ! done
201+ end if
202+ end if
203+
204+ ! in this case assuming it's a space, so use intrinsic functions
205+ newstr = trim (adjustl (str))
206+
207+ end function strip
208+ ! *****************************************************************************************
209+
155210! *****************************************************************************************
156211 end module string_module
157212! *****************************************************************************************
0 commit comments