Skip to content

Methods Summary ​

Every type-bound procedure of string and every procedure of the module, with its arguments (the optional ones in brackets). The pages of the reference explain them with examples; the API documents the source.

Fortran Built-in Replacements ​

These generic interfaces shadow Fortran intrinsics so they accept type(string) arguments transparently:

NameIntrinsic replaced
adjustlADJUSTL
adjustrADJUSTR
countCOUNT
indexINDEX
len_trimLEN_TRIM
repeatREPEAT
scanSCAN
trimTRIM
verifyVERIFY

INFO

len is available as a type-bound method (s%len()) but is not re-exported as a module-level generic to avoid conflicts with the intrinsic in certain compilers.

Transformation Methods ​

MethodDescription
adjustl()Left-adjust (move leading spaces to the end)
adjustr()Right-adjust (move trailing spaces to the beginning)
camelcase([sep])All words capitalized, separators removed
capitalize()First character upper, rest lower
center(width[, fill_char])Centered in width characters, as Python str.center
colorize([color_fg][, color_bg][, style])ANSI terminal colorization via FACE; returns character
common_prefix(other) / common_prefix(array)Longest common prefix shared with another string/character, or with all elements of a string array
edit_distance(other[, by])Levenshtein distance from another string or character, in bytes or with by=SF_CHARS in characters
compact([sep][, unicode])Words separated by one sep (default space), whitespace runs collapsed and the ends removed; unicode=.true.: Unicode White_Space
decode(codec)Decode; codec='base64' is the only codec available, an unknown one gives a not allocated string
encode(codec)Encode; codec='base64' is the only codec available, an unknown one gives a not allocated string
escape(to_escape[, esc])Escape the character to_escape with a backslash (or with esc)
expand_tabs([tab_size])Tabs replaced by spaces up to the next tab stop, every tab_size columns (default 8)
fill(width[, right][, filling_char])Pad with zeros (or custom char) to reach width
hex([bits][, uppercase])Hexadecimal representation of the integer held by the string (two's complement on bits bits, default 64)
insert(substring, pos)Insert substring at given position
join(array[, sep])Join an array of strings or characters with receiver as default separator
justify(lines, width)Pack the words into fully justified lines (subroutine, allocates lines)
ljust(width[, fill_char])Left justified in width characters, as Python str.ljust
lower()All characters lowercase
lstrip([remove][, whitespace][, unicode])As strip, the leading characters only
partition([sep])Split at the first sep (default space); return string(3) = [before, sep, after]
quote([quote_char])Between quotes (default "), the inner ones doubled
repeat(ncopies)Concatenate ncopies copies of the string
replace(old, new[, count])Replace all (or the first count) occurrences of old with new, left to right; the replaced text is not searched again
reverse()Reverse character order
reverse_words([sep])Reverse the order of the words
rjust(width[, fill_char])Right justified in width characters, as Python str.rjust
rstrip([remove][, whitespace][, unicode])As strip, the trailing characters only
slice([first][, last][, stride])Section first:last:stride, bounds clamped into the string; returns character
snakecase([sep])Words lowercase, joined by _
split(tokens[, sep][, max_tokens][, keep_empty])Tokenize into allocatable array (subroutine); sequential separators count as one, a string of only separators has no tokens; with keep_empty the empty fields are tokens
split_chunked(tokens, chunks[, sep])Tokenize in chunks of chunks tokens (subroutine)
squeeze([set])Runs of a repeated character (of set if passed) reduced to one, as tr -s
startcase([sep])Title case — each word capitalized
strip([remove_nulls][, remove][, whitespace][, unicode])Remove leading/trailing spaces, or the characters of the set remove, and all the whitespace if whitespace (Unicode White_Space with unicode=.true.)
swapcase()Swap upper↔lower case
transliterate(old_set, new_set)Characters of old_set replaced by the ones of new_set, as tr
trim()Remove trailing spaces
unescape(to_unescape[, unesc])Remove the backslash (or unesc) escaping the character to_unescape
unique([substring])Collapse repeated occurrences of substring (default space) to one
unquote()Inverse of quote, for a string between the same ' or "
upper()All characters uppercase

Inquiry Methods ​

MethodReturnsDescription
chars()character(:)Raw character data (null if not allocated)
compare_version(other[, sep])integerField-by-field version comparison: -1, 0 or 1
count(substring[, ignore_isolated][, overlapping])integerNumber of occurrences, not overlapping unless overlapping=.true.
end_with(suffix[, start][, end][, ignore_null_eof])logicalTrue if string ends with suffix
index(substring[, back][, occurrence])integerPosition of substring (like INDEX); occurrence=k gives the k-th one
is_allocated()logicalTrue if raw member is allocated
is_alnum()logicalTrue if all characters are letters or digits
is_alpha()logicalTrue if all characters are letters
is_digit()logicalTrue if all characters are digits
is_integer([allow_spaces])logicalTrue if string represents an integer
is_lower()logicalTrue if all characters are lowercase
is_number([allow_spaces])logicalTrue if string represents an integer or real
is_punct()logicalTrue if all characters are punctuation (as C ispunct)
is_real([allow_spaces])logicalTrue if string represents a real: a decimal point or an exponent is required, an integer is not a real
is_space([unicode])logicalTrue if all characters are whitespace (as C isspace; unicode=.true.: Unicode White_Space)
is_upper()logicalTrue if all characters are uppercase
is_xdigit()logicalTrue if all characters are hexadecimal digits
match(pattern)logicalTrue if the whole string matches a wildcard pattern (*, ?, [seq], [!seq])
len()integerTotal length (like LEN)
len_last_word([sep])integerLength of the last word, trailing separators ignored
len_trim()integerLength without trailing spaces
scan(set[, back])integerPosition of the first character belonging to set (like SCAN)
start_with(prefix[, start][, end])logicalTrue if string starts with prefix
verify(set[, back])integerPosition of the first character not belonging to set (like VERIFY)

UTF-8 Methods ​

A unit is a well-formed UTF-8 sequence or a single byte that is not part of one: see Unicode and UTF-8. Positions, lengths and widths count bytes; len, index, scan, verify, slice, insert, len_last_word, center, ljust, rjust, fill, justify and expand_tabs take by=SF_CHARS to count characters instead; the width methods also take by=SF_COLUMNS, display columns. reverse, match, scan, verify, squeeze, transliterate and the remove= set of strip, lstrip and rstrip work on units; positions and lengths count bytes.

MethodReturnsDescription
has_bom()logicalTrue if the string starts with a UTF-8 byte order mark (EF BB BF)
escape_c([ascii])stringC escapes for what is not printable ASCII (ascii=.false.: only controls and ill-formed bytes)
escapes_error()integerByte position of the first malformed C escape, 0 if none
escape_xml([attribute])string& < > " ' as &amp; &lt; &gt; &quot; &apos;; attribute=.true.: TAB, LF, CR as &#9; &#10; &#13; too
width()integerDisplay width in terminal columns (East Asian wide 2, zero-width 0, controls 0)
byte_pos(char_pos)integerByte position of the first byte of the character number char_pos
char_pos(byte_pos)integerNumber of the character holding the byte at byte_pos
codepoints()integer(I4P)(:)Codepoints, one per unit; a byte not part of a well-formed sequence is minus its value
is_utf8()logicalTrue if the string is well-formed UTF-8
unescape_c()stringC escapes (\n, \xHH, \uXXXX, ...) expanded; \xHH and octal give bytes, \u and \U codepoints
unescape_xml()stringThe 5 predefined XML entities and &#N;, &#xH; expanded (codepoints in UTF-8)
to_valid_utf8([replacement])stringEach ill-formed sequence replaced by U+FFFD (or replacement)
utf8_error()integerByte position of the first ill-formed byte, 0 if none
xml_error()integerByte position of the & of the first malformed XML reference, 0 if none

Number Casting ​

MethodDescription
to_number(kind)Cast string to the numeric kind of the kind argument
read_number(number[, iostat][, iomsg])Cast string to the kind of number, reporting a failure in iostat/iomsg (elemental subroutine)

The module procedure shortest(number) (R4P, R8P) returns a string, the shortest text that reads back as exactly number.

The kind argument selects the return type — pass any literal of the target PENF kind:

fortran
real(R8P)    :: x
integer(I4P) :: n

x = s%to_number(kind=1._R8P)
n = s%to_number(kind=0_I4P)

A cast to a real kind accepts both real and integer strings; a cast to an integer kind requires an integer string. If the string does not hold a suitable number the result is 0 for an integer kind and a quiet NaN for a real kind: check with is_number / is_integer first to tell a parsed 0 from a failure, or use read_number, which reports it.

File I/O Methods (type-bound) ​

MethodDescription
read_file(file[, is_fast][, form][, iostat][, iomsg][, skip_bom])Read entire file into this string; skip_bom=.true. drops a leading UTF-8 BOM
read_line(unit[, form][, iostat][, iomsg])Read one line from connected unit
read_lines(unit[, form][, iostat][, iomsg][, skip_bom])Read all lines from connected unit; skip_bom as read_file
write_file(file[, form][, iostat][, iomsg][, bom])Write this string to file; bom=.true. starts it with a UTF-8 BOM
write_line(unit[, form][, iostat][, iomsg])Write one line to connected unit
write_lines(unit[, form][, iostat][, iomsg])Write all lines to connected unit

File I/O Subroutines (module-level) ​

fortran
call read_file(file, lines[, form][, iostat][, iomsg][, skip_bom])
call read_lines(unit, lines[, form][, iostat][, iomsg][, skip_bom])
call write_file(file, lines[, form][, iostat][, iomsg][, bom])
call write_lines(unit, lines[, form][, iostat][, iomsg])

lines is type(string), allocatable :: lines(:) for read_* and type(string), intent(in) :: lines(1:) for write_*.

Path / Search Methods ​

MethodDescription
basedir([sep])Directory component of a path
basename([sep][, extension][, strip_last_extension])File name component, optionally stripped
extension()File extension (with leading dot)
glob(pattern, list)Pathnames matching a shell pattern, only its wildcards special; list is a string or character allocatable array (subroutine, Unix only)
search(tag_start, tag_end[, in_string][, in_character][, istart][, iend])Find first region delimited by tags
tempname([is_file][, prefix][, path])Generate a unique temporary file/directory name

Miscellaneous ​

MethodDescription
free()Deallocate raw member
strjoin(array[, sep][, is_trim][, is_col])Join 1D or 2D arrays with separator; is_trim applies to character arrays, is_col to 2D ones

Regular Expressions ​

type(regex) and type(regex_match), see Regular Expressions. The subject is a character or a string.

Method of regexReturnsDescription
compile(pattern[, flags][, iostat][, iomsg])(subroutine)Compile a pattern; flags i, m, s; the error position in iostat
search(subject[, start])regex_matchLeftmost match from the byte start
match(subject[, start])regex_matchMatch starting at start
fullmatch(subject[, start])regex_matchMatch from start to the end
finditer(subject[, start])regex_match(:)All the matches, left to right
findall(subject[, group])string(:)Text of a group of every match
split(subject[, maxsplit])string(:)Pieces between the matches, group texts included
sub(repl, subject[, count][, nsub][, iostat][, iomsg])stringMatches replaced by a template (\1, \g<name>, \g<0>)
group_count(), group_index(name), is_compiled()integer, integer, logicalNumber of groups, number of a named group, compiled
Member of regex_matchReturnsDescription
foundlogicalTrue if there is a match
span(group)integer(2)First and last byte of a group (number or name); [0, -1] if it did not match
group(group)stringText of a group (number or name); not allocated if it did not match
groups()string(:)Texts of the groups 1..n

Module-Level Procedures ​

ProcedureDescription
from_codepoints(codes)String encoded in UTF-8 from codepoints, the inverse of codepoints()
glob(self, pattern, list)Glob search returning matching paths; self is a string
strjoin(array[, sep][, is_trim][, is_col])Join arrays of strings or characters
re_search(subject, pattern[, flags][, start]), re_fullmatch(subject, pattern[, flags])Match a pattern (a character or a compiled regex)
re_findall(subject, pattern[, flags][, group]), re_split(subject, pattern[, flags][, maxsplit])All the matches, the pieces between them
re_sub(subject, pattern, repl[, flags][, count])Replace the matches of a pattern
strsort(strings[, index][, less])Sort an array of strings in place (subroutine): stable merge sort, index the permutation, less the order
strless(a, b), strless_nocase(a, b), strless_natural(a, b)Orders for strsort: byte (the default), ASCII case ignored, natural (file2 before file10)
read_file, read_linesFile reading subroutines
write_file, write_linesFile writing subroutines

Operators ​

OperatorLeftRightReturnsDescription
=stringstring, character, or any PENF numeric—Assignment
//stringstring or charactercharacterConcatenation
.cat.stringstring or characterstringConcatenation
==stringstring or characterlogicalEquality
/=stringstring or characterlogicalInequality
<stringstring or characterlogicalLexicographic less-than
<=stringstring or characterlogicalLess-or-equal
>=stringstring or characterlogicalGreater-or-equal
>stringstring or characterlogicalGreater-than

PENF Kind Parameters ​

Re-exported from PENF for convenience:

I1P, I2P, I4P, I8P, R4P, R8P, R16P

  • R16P support (assignment and to_number) requires the -DPENF_R16P preprocessor flag.
  • I2P support is disabled when the _NVF macro is defined (NVIDIA Fortran compatibility).

Unit Constants ​

ConstantMeaning
SF_BYTESby= unit: bytes, the default
SF_CHARSby= unit: characters (UTF-8 units)
SF_COLUMNSby= unit of the width methods: display columns

Character Kind Constant ​

CK — the default character kind (selected_char_kind('DEFAULT')). Use it when defining character variables that will interact with the raw member:

fortran
character(kind=CK, len=:), allocatable :: buf