Skip to content

Commit 585d8b5

Browse files
authored
Modify Reverse String in Fortran (#5122)
Improve Reverse String Fortran code snippet
1 parent e9077e1 commit 585d8b5

File tree

1 file changed

+34
-13
lines changed

1 file changed

+34
-13
lines changed
Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,34 @@
1-
program reversestring
2-
character(len=100) :: argument
3-
character(len=:), allocatable :: buff, reversed
4-
integer :: i, n
5-
call GET_COMMAND_ARGUMENT(1,argument)
6-
allocate (buff, mold=argument)
7-
n = len(argument)
8-
do i = 0, n - 1
9-
buff(n-i : n-i) = argument(i+1 : i+1)
10-
end do
11-
reversed = adjustl(trim(buff))
12-
write(*,'(g0.8)')reversed
13-
end program reversestring
1+
program reverse_string
2+
implicit none
3+
character(len=:), allocatable :: arg, rev
4+
integer :: i, n, error
5+
6+
if (command_argument_count() < 1) then
7+
print '("")'
8+
stop
9+
end if
10+
11+
! Get length of argument
12+
call get_command_argument(1, length=n, status=error)
13+
if (error /= 0 .or. n == 0) then
14+
print '("")'
15+
stop
16+
end if
17+
18+
! Allocate and read argument
19+
allocate(character(len=n) :: arg)
20+
call get_command_argument(1, arg, status=error)
21+
if (error /= 0) then
22+
print '("")'
23+
deallocate(arg)
24+
stop 0
25+
end if
26+
27+
! Allocate and create reversed string
28+
allocate(character(len=n) :: rev)
29+
do i = 1, n
30+
rev(i:i) = arg(n-i+1:n-i+1)
31+
end do
32+
33+
print '(A)', rev
34+
end program reverse_string

0 commit comments

Comments
 (0)