Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Functions for the built-in string type #866

Open
Beliavsky opened this issue Aug 25, 2024 · 1 comment
Open

Functions for the built-in string type #866

Beliavsky opened this issue Aug 25, 2024 · 1 comment

Comments

@Beliavsky
Copy link

Beliavsky commented Aug 25, 2024

A few string functions I would like are

  1. count_char -- Count the number of times a single character c appears in a character variable s
  2. pos_char -- Returns an integer array of the positions where c appears in s
  3. replace -- Replace character a with b in s
  4. compress -- Replace 2 or more consecutive occurrences of a character in s with a single occurrence. This is useful for replacing multiple spaces with a single space.
  5. upper_case
  6. lower_case

Here is an implementation of count_char.

module string_funcs_mod
implicit none
private
public :: count_char
contains
elemental function count_char(s, c) result(ncount)
! count the number of times character c appears in string s
    character(len=*), intent(in) :: s
    character, intent(in) :: c
    integer :: ncount, i, len_trim_s
    len_trim_s = len_trim(s)
    ncount = 0
    do i = 1, len_trim_s
       if (s(i:i) == c) ncount = ncount + 1
    end do
    if (c == ' ') ncount = ncount + len(s) - len_trim_s
end function count_char
end module string_funcs_mod
!
program xstring_funcs
use string_funcs_mod
implicit none
print "(*(1x,i0))", count_char("hello world ", ["l", "a", " "])
end program xstring_funcs

output:
3 0 2

@ivan-pi
Copy link
Member

ivan-pi commented Jan 6, 2025

Functions 5 and 6 are available in stdlib_ascii as to_upper/to_lower. Also available for type(string_type) in stdlib_string_type.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants