program sort_and_replace
implicit none
character(len=50), dimension(5) :: str_array = ['banana', 'apple', 'cherry', 'date', 'fig']
character(len=50) :: temp
integer :: i, j
integer :: len_str
! 按字典序排序
do i = 1, size(str_array) - 1
do j = i + 1, size(str_array)
if (str_array(i) > str_array(j)) then
temp = str_array(i)
str_array(i) = str_array(j)
str_array(j) = temp
end if
end do
end do
! 将字母 'a' 替换为 'A'
do i = 1, size(str_array)
len_str = len_trim(str_array(i))
do j = 1, len_str
if (str_array(i)(j:j) == 'a') then
str_array(i)(j:j) = 'A'
end if
end do
end do
! 输出结果
do i = 1, size(str_array)
print *, str_array(i)
end do
end program sort_and_replace
关键步骤解释:
- 定义字符串数组:
character(len=50), dimension(5) :: str_array = ['banana', 'apple', 'cherry', 'date', 'fig']
定义了一个长度为50的字符串数组 str_array
,并初始化了5个字符串。
- 按字典序排序:
do i = 1, size(str_array) - 1
do j = i + 1, size(str_array)
if (str_array(i) > str_array(j)) then
temp = str_array(i)
str_array(i) = str_array(j)
str_array(j) = temp
end if
end do
end do
使用冒泡排序算法对字符串数组进行排序。比较相邻的两个字符串,如果前一个字符串大于后一个字符串,则交换它们的位置。
- 替换字母 'a' 为 'A':
do i = 1, size(str_array)
len_str = len_trim(str_array(i))
do j = 1, len_str
if (str_array(i)(j:j) == 'a') then
str_array(i)(j:j) = 'A'
end if
end do
end do
遍历每个字符串,获取其有效长度,再遍历每个字符,如果字符是 'a',则将其替换为 'A'。
- 输出结果:
do i = 1, size(str_array)
print *, str_array(i)
end do
输出排序并替换后的字符串数组。