Strip control codes and extended characters from a string: Difference between revisions

no edit summary
(→‎{{header|MATLAB}} / {{header|Octave}}: remove control codes from string)
No edit summary
Line 138:
</PRE>
 
=={{header|Fortran}}==
<lang fortran>module stripcharacters
 
contains
 
pure integer function ascancontrol(chararray)
integer, intent(in) :: chararray(:)
integer :: i
do i=1,size(chararray)
if ( chararray(i) < 32 .or. chararray(i) == 127 ) then
ascancontrol = i
return
end if
end do
ascancontrol = 0
end function ascancontrol
pure integer function ascanextended(chararray)
integer, intent(in) :: chararray(:)
integer :: i
do i=1,size(chararray)
if ( chararray(i) < 32 .or. chararray(i) > 126 ) then
ascanextended = i
return
end if
end do
ascanextended = 0
end function ascanextended
pure subroutine strip(string,ascan)
character(len=*), intent(inout) :: string
integer :: old, new, stride
integer :: ascii(len(string))
interface
pure integer function ascan(chararray)
integer, intent(in) :: chararray(:)
end function ascan
end interface
forall (i=1:len(string)) ascii(i) = iachar(string(i:i))
old = 1; new = 1
do
stride = ascan( ascii( old : ) )
if ( stride > 0 ) then
ascii( new : new+stride-2 ) = ascii( old : old+stride-2 )
old = old+stride
new = new+stride-1
else
ascii( new : ) = ascii( old : )
forall (i=1:len(string)) string(i:i) = achar(ascii(i))
return
end if
end do
end subroutine strip
 
end module stripcharacters
 
program test
use stripcharacters
character(len=256) :: string
integer :: ascii(256), i
forall (i=0:255) ascii(i) = i
forall (i=1:len(string)) string(i:i) = achar(ascii(i))
write (*,*) string
call strip(string,ascancontrol)
write (*,*) 'Control characters deleted:'
write (*,*) string
 
forall (i=1:len(string)) string(i:i) = achar(ascii(i))
call strip(string,ascanextended)
write (*,*) 'Extended characters deleted:'
write (*,*) string
 
end program test</lang>
=={{header|Go}}==
Go works for ASCII and non-ASCII systems. The first pair of functions below interpret strings as byte strings, presumably useful for strings consisting of ASCII and 8-bit extended ASCII data. The second pair of functions interpret strings as UTF-8.
24

edits