在Ubuntu上進行Fortran字符串操作,你可以使用Fortran的內置函數和特性。以下是一些基本的字符串操作示例:
//
操作符可以將兩個字符串連接起來。program string_concatenation
implicit none
character(len=10) :: str1 = 'Hello'
character(len=10) :: str2 = 'World'
character(len=20) :: result
result = str1 // ' ' // str2
print *, result
end program string_concatenation
len
函數可以獲取字符串的長度。program string_length
implicit none
character(len=10) :: str = 'Hello'
integer :: length
length = len(str)
print *, 'The length of the string is:', length
end program string_length
program string_slicing
implicit none
character(len=10) :: str = 'Hello'
character(len=5) :: substring
substring = str(1:5)
print *, 'Substring:', substring
end program string_slicing
program string_replace
implicit none
character(len=10) :: str = 'Hello World'
character(len=11) :: new_str
new_str = replace_substring(str, 'World', 'Fortran')
print *, 'New string:', new_str
contains
function replace_substring(original, old, new) result(replaced)
character(len=*), intent(in) :: original, old, new
character(len=:), allocatable :: replaced
integer :: pos, old_len, new_len
old_len = len(old)
new_len = len(new)
pos = index(original, old)
if (pos /= 0) then
replaced = original(1:pos-1) // new // original(pos+old_len:)
else
replaced = original
end if
end function replace_substring
end program string_replace
achar
和ichar
用于字符和ASCII碼之間的轉換,trim
用于去除字符串尾部的空格。program string_conversion
implicit none
character(len=1) :: char_val = 'A'
integer :: int_val
int_val = ichar(char_val)
print *, 'The ASCII value of', char_val, 'is', int_val
char_val = achar(int_val)
print *, 'The character for ASCII value', int_val, 'is', char_val
character(len=10) :: str = 'Hello '
print *, 'Trimmed string:', trim(str)
end program string_conversion
請注意,上述代碼示例需要在支持Fortran的編譯器(如gfortran)下編譯和運行。你可以使用以下命令來編譯Fortran程序:
gfortran -o program_name source_file.f90
然后運行生成的可執行文件:
./program_name
確保你的Ubuntu系統中已經安裝了gfortran編譯器。如果沒有安裝,可以使用以下命令進行安裝:
sudo apt update
sudo apt install gfortran