Removing whitespace in string - fortran

I have the following code:
program main
character (len=15) :: abc = "te st tex t"
print *, trim(abc)
end program main
Which outputs:
te st tex t
I excepted all the whitespace to be removed but it wasn't. How can I remove all the whitespace from the string?

Trim will remove spaces only at the edges, not in the middle (this is common behaviour on almost all languages/libraries). If you want to remove all spaces in the string, you will have to create your own function to do this, iterating through the string.
Ex.:
program Test
implicit none
! Variables
character(len=200) :: string
! Body of Test
string = 'Hello World 7 9'
print *, string
call StripSpaces (string)
print *, string
contains
subroutine StripSpaces(string)
character(len=*) :: string
integer :: stringLen
integer :: last, actual
stringLen = len (string)
last = 1
actual = 1
do while (actual < stringLen)
if (string(last:last) == ' ') then
actual = actual + 1
string(last:last) = string(actual:actual)
string(actual:actual) = ' '
else
last = last + 1
if (actual < last) &
actual = last
endif
end do
end subroutine
end program Test
This was tested on intel compiler, not on gfortran, but I think it will work.

I was able to do this using the variable string library described here ( http://schonfelder.co.uk/is1539-2-99.htm ). The source code link is found in the introduction section of the ISO document.
Here is the code
program Console1
use ISO_VARYING_STRING
implicit none
! Body of Console1
character(LEN=50) :: text = 'Hello World John Mary '
character(LEN=50) :: res
print *, trim(text)
! 'Hello World John Mary'
res = REPLACE(text,' ','', every=.TRUE.)
print *, trim(res)
! 'HelloWorldJohnMary'
end program Console1

Here's a dirty, shameful way to eliminate the spaces. This is only likely to work if a compiler lays out a length-15 string in the same order and space as it would a 15-element array of characters. While this is likely to be true, and in my recent experience is true, it is not guaranteed to be so by the standard. That aside, this approach may be good enough.
! declarations
CHARACTER (len=15) :: abc = "te st tex t"
CHARACTER, DIMENSION(LEN(abc)) :: abc_array
! or CHARACTER, DIMENSION(:), ALLOCATABLE :: abc_array if your compiler supports
! automatic allocation
! transfer the string into an array of characters
abc_array = TRANSFER(abc,abc_array)
! eliminate the spaces, and transfer back to the string
abc = TRANSFER(PACK(abc_array,abc_array/=' '),abc)
! now all the spaces are at the end of abc so the following statement writes the
! string with no spaces
WRITE(*,*) TRIM(abc)
Use this approach at your own risk.

For those averse to TRANSFER perhaps a nice little recursive function would appeal. As written this depends on Fortran 2003's ability to automatically allocate character scalars, but it shouldn't be too hard to modify if your compiler doesn't support this feature yet.
RECURSIVE FUNCTION stripper(string,ch) RESULT(stripped)
CHARACTER(len=*), INTENT(in) :: string
CHARACTER, INTENT(in) :: ch
CHARACTER(:), ALLOCATABLE :: stripped
IF (LEN(string)==1) THEN
IF (string==ch) THEN
stripped = ''
ELSE
stripped = string
END IF
ELSE
IF (string(1:1)==ch) THEN
stripped = stripper(string(2:),ch)
ELSE
stripped = string(1:1)//stripper(string(2:),ch)
END IF
END IF
END FUNCTION stripper

You can try this:
program test
!erase blank space in a string
!run over every character of the string and just take every non-blank in other variable.
implicit none
character (len=100) str1,str2
integer i
str2='' !in this variable will be save non-blank spaces
str1=' a b c de ' !Test string with blank spaces
write(*,*)len_trim(str1), str1
do i=1,len(str1)
if (str1(i:i).ne.' ')str2=trim(str2)//trim(str1(i:i))
end do
write(*,*)len_trim(str2), str2
end

Related

Combining strings and integers to make a variable format: Missing initial left parenthesis in format (Fortran)

I want to make a variable format for my "write" statement. To do so, I wrote a small program (nvari is the variable):
program VariableFormat
implicit none
integer :: x = 1,y = 2, z = 3, i, nvari
double precision :: pi = 3.14
integer, allocatable :: var(:)
integer :: A(3) = (/1,2,3/)
character(100) :: fmt,fmt2,str1,str2,str3
print*, size(A)
allocate(var(size(A)))
do i = 1, size(A)
var(i) = A(i)
end do
nvari = 2
!
! first part
!
fmt = '(a,f4.2)'
write(*,fmt) "The value of pi is ", pi
!
! second part
!
write (str1, "(1A2,1I1,1A1,1I2,1A1)") "'(", 3, "I", 15, ","
print*, str1
write(str2,'(I10)') nvari
print*, str2
write (str3, "(1A1,1I2,1A2)") "I", 15, ")'"
print*, str3
fmt2 = trim(adjustl(str1))//trim(adjustl(str2))//trim(adjustl(str3))
print*, fmt2
write(*,fmt2) x,y,z,(var(i),i=1,nvari)
end program VariableFormat
First question:
It can be seen that fmt2 is similar to fmt in the sense that in both we have '(X,Y)'.
However, while the first part of the code is executed correctly, for the second part, I have the error:
At line 32 of file VariableFormat.F90 (unit = 6, file = 'stdout')
Fortran runtime error: Missing initial left parenthesis in format
'(3I15,2I15)'
I don't understand which parenthesis is missing as fmt2 is similar to fmt.
To execute my program I use the gfortran compiler: gfortran -o binary_VariableFormat VariableFormat.F90 and then:./binary_VariableFormat
Second question:
Is there a way to write fmt2 in a more compact way?
This is perhaps more a misunderstanding about character variables and literal constants than about formats.
In
fmt = '(a,f4.2)'
we have the character variable's name (fmt) on the left-hand side of the assignment and the value to assign on the right. '(a,f4.2)' is a literal character constant and its value is given to fmt.
The two, matching, ''s act as delimiters for the value of the constant: they are not themselves part of the value.1 The value of the literal constant is (a,f4.2). Go on, print the value of fmt to check. (One actually has to do something quite different to get the value of a character variable with delimiters.)
A character value in a format must be something like (...): the first non-blank value must be a (. Because you've set the value to be like '(...)' the compiler is (quite rightly) complaining.
Where we have something like
write(str2,'(I10)') nvari
we are using this literal constant which has value (I10) not '(I10)'. If we instead had
write(str2,"'(I10)'") nvari
we'd see exactly the same complaint (or perhaps a complaint when compiling instead of running).
Finally, note that when using a FORMAT statement (many here really don't like such things), we'd not have these delimiters at all:
format (I10) ! Correct
format '(I10)' ! Badly wrong
1 Similarly, if we have literal constants used like
complex :: a = (1., 2.)
integer :: i = INT(B'001')
the delimiters for the complex and BOZ literal constants are not part of the value. Equally in an array constructor like [0,1,2,3] the square brackets are a delimiter part of the syntax rather than the value.

How to split string to characters in Fortran?

I am working on ciphering program, where ull put text and it will convert it into coded message. I stick and point where I dont know how to split len into sepparate characters. Is it even possible?
Yes, you can split a string into a character array. If chararray = "abcdefg" then you can have an array like ca(1) = chararray(1:1), ca(2) = chararray(2:2) ...
ca(7:7) = chararray(7)
This can also be done in a do-loop using the iachar and achar functions.
program test
character*7 :: stringin
integer :: single_character
stringin = 'message'
do i = 1, len(stringin), 1
single_character = iachar(stringin(i:i))
write(*,*) achar(single_character)
end do
end program
This creates an integer representation of the letters with iachar and converts them back with achar. This may be helpful if using a mathematical expression to do the encoding.
More information can be found here

How do I repeat one string to match the length of another string?

I am trying to repeat the string "k" to match the length of "text" without going over the length. So it would output "treetreetreetreetreet" and not "treetreetreetreetreetree". I really dont know where to start other than just outputing more characters than needed.
PROGRAM test
IMPLICIT NONE
CHARACTER*30 :: text, k
INTEGER :: times
text = 'hello my name is anon'
k = 'tree'
times = (LEN_TRIM(text)/LEN_TRIM(k)) + 1
WRITE(*,*) REPEAT(k,times)
END PROGRAM test
First, your sample program as-is doesn't produce treetreetreetreetreetree as you expect, it actually produces tree tree tree .... When you pass the string k to REPEAT, the spaces after tree also get repeated. You should trim the string before repeating it, such as REPEAT(trim(k),times).
There are several ways to solve your main problem - I recommend using what you have so far but reducing the final result to the length you want - in this case LEN_TRIM(text). A good way to do this is to store the output of REPEAT in a temporary variable and output only a subset of this final string.
With both of these modifications and some other cleanup, your code looks like:
program main
implicit none
character(len=30) :: text, k, str
integer :: times
text = 'hello my name is anon'
k = 'tree'
times = (LEN_TRIM(text)/LEN_TRIM(k)) + 1 ! -- Note integer division
str = REPEAT(trim(k),times)
write(*,*) str(1:LEN_TRIM(text))
end program main
which gives the desired output
> gfortran main.f90 && ./a.out
treetreetreetreetreet

Fortran - String with unknown characters into substrings

I am trying to put an input string into sub-string arrays. The number of data in the input file are less than 10 but unknown. The number of spaces between each data is also unclear.
Example:
Asd B Cwqe21 Ddsw Eww
I am quite novice to Fortran, so I do not know which format I should use. My problem is that I do not know the number of data (here I assumed that there are 5), so how can I make the code work?
I tried the following which did not work:
CHARACTER (LEN=100), DIMENSION(10) :: string
READ (1,*) (string,I=1,10)
It seems that the error I got was because there was no 6th string to read and put into string(6).
I tried using the "Index" to find the space, but since I do not know how many spaces are in the string, it did not help me.
I don't know if this is more or less elegant/efficient than the standard approach in M.S.B's comment, but an interesting alternative.
integer istart,nw
character (len=100) line,wd,words(100)
open(1,file='t.dat')
read(1,'(a)')line
istart=1
nw=0
do while(len(trim(line(istart:))).gt.0)
read(line(istart:),*)wd
istart=istart+index(line(istart:),trim(wd))+len(trim(wd))
nw=nw+1
words(nw)=trim(wd)
enddo
write(*,*)trim(line)
write(*,*)('/',trim(words(k)),k=1,nw),'/'
end
An inefficient approach that is simple to program is to try to read the maximum number of items, and if this fails to successively try to read one fewer items until the read is successful, as shown below:
program xread_strings
integer, parameter :: nw = 10
character (len=1000) :: text
character (len=20) :: words(nw)
integer :: i,ierr,nread
text = "Asd B Cwqe21 Ddsw Eww"
nread = 0
do i=nw,1,-1
read (text,*,iostat=ierr) words(:i)
if (ierr == 0) then
nread = i
exit
end if
end do
if (nread > 0) write (*,*) "read ",nread," words: ",("'"//trim(words(i)) // "' ",i=1,nread)
end program xread_strings
! g95 Output:
! read 5 words: 'Asd' 'B' 'Cwqe21' 'Ddsw' 'Eww'

way Fortran handles empty spaces

I would like to have some clarifications about the way Fortran handles "empty" characters in strings.
Let us assume we have this situation:
program main
implicit none
test('AB')
end program
where
function test(name)
implicit none
character(10) :: name
character(3) :: cutname
write(*,*) '-'//name//'-' ! Gives output "-AB -"
! Space has then been added at the end
cutname(1:3) = name(1:3)
write(*,*) '1-'//cutname//'-' ! Gives output "-AB -"
! It seems there is a space then at the end
! of cutname
write(*,*) (cutname(1:2) == 'AB') ! Gives output T (true)
write(*,*) (cutname(3:3) == ' ') ! Gives output F (false)
write(*,*) (cutname == 'AB ') ! Gives output F (false)
end function
I am pretty curious about what is happening in this case.
Thanks in advance.
Standard strings in Fortran are fixed length. If you don't use the entire string, they are padded on the end with blanks/spaces.
I altered your example program to pass compiler checks of gfortran and ifort. Your function had no return, so better as a subroutine. The compilers noticed the inconsistency between the lengths of the actual and dummy argument -- because I put the procedure into a module and useed it so that the compiler could check argument consistency. They complain about passing a length 2 string to a length 10 string. How are the remaining characters supposed to be defined?
module test_mod
contains
subroutine test(name)
implicit none
character(10) :: name
character(3) :: cutname
write(*,*) '-'//name//'-' ! Gives output "-AB -"
! Space has then been added at the end
cutname(1:3) = name(1:3)
write(*,*) '1-'//cutname//'-' ! Gives output "-AB -"
! It seems there is a space then at the end
! of cutname
write(*,*) (cutname(1:2) == 'AB') ! Gives output T (true)
write(*,*) (cutname(3:3) == ' ') ! Gives output F (false)
write(*,*) (cutname == 'AB ') ! Gives output F (false)
end subroutine test
end module test_mod
program main
use test_mod
implicit none
call test('AB ')
end program
When I run this version, the outputs are T, T and T, which is what I expect.
EDIT: I suggest using full warning and error checking options of your compiler. That is how I quickly found the issues with the example. With gfortran: -O2 -fimplicit-none -Wall -Wline-truncation -Wcharacter-truncation -Wsurprising -Waliasing -Wimplicit-interface -Wunused-parameter -fwhole-file -fcheck=all -std=f2008 -pedantic -fbacktrace.
A string assignment statement doesn't require the two sides to have the same lengths. If the RHS is shorter than the string variable on the LHS, it will get padded on the end with blanks. Here, the arguments should be consistent, including in length.