diff --git a/src/stdlib_strings.fypp b/src/stdlib_strings.fypp index 0d3904fbf..9cacb1f72 100644 --- a/src/stdlib_strings.fypp +++ b/src/stdlib_strings.fypp @@ -302,12 +302,21 @@ contains last = len(string) nsub = len(substring) - if (nsub > 0) then - do while(string(last-nsub+1:last) == substring) - last = last - nsub + if (nsub > 0 .and. nsub <= last) then + do while(last >= nsub) + if (string(last-nsub+1:last) == substring) then + last = last - nsub + else + exit + end if end do end if - chomped_string = string(1:last) + + if (last <= 0) then + chomped_string = '' + else + chomped_string = string(1:last) + end if end function chomp_substring_char_char diff --git a/test/string/test_string_strip_chomp.f90 b/test/string/test_string_strip_chomp.f90 index 095a53c3b..b7a9b9c93 100644 --- a/test/string/test_string_strip_chomp.f90 +++ b/test/string/test_string_strip_chomp.f90 @@ -151,6 +151,8 @@ subroutine test_chomp_substring_char(error) call check(error, chomp("hellooooo", "oo") == "hello") if (allocated(error)) return call check(error, chomp("hellooooo", substring="oo") == "hello") + if (allocated(error)) return + call check(error, chomp("helhel", substring="hel") == "") end subroutine test_chomp_substring_char subroutine test_chomp_substring_string(error)