Character Variables in Fortran

In Fortran, character variables are used to store textual information, such as letters, words, or entire strings. Unlike numeric variables that store integers or floating-point numbers, character variables hold sequences of characters, enabling programs to handle names, labels, messages, and other textual data. Character variables are essential in scientific computing for reporting results, creating user interfaces, managing file names, and labeling arrays or data outputs.

Fortran provides a rich set of features for working with character data, including variable-length strings, concatenation, slicing, intrinsic string functions, and formatting. Understanding character variables thoroughly allows programmers to process and manipulate text efficiently, enhancing the readability and functionality of their programs.

What is a Character Variable?

A character variable is a named storage location that can hold a sequence of characters. Each character occupies one byte of memory, and the total length of the variable determines how many characters it can store. For example, the variable name in the following declaration can hold up to 10 characters:

character(len=10) :: name

Here:

  • character specifies the data type.
  • len=10 indicates that the variable can hold a maximum of 10 characters.
  • name is the variable identifier.

After declaration, a value can be assigned to the variable:

name = "Fortran"
print *, "Name:", name

Output:

Name: Fortran

Even though len=10, the variable contains only 7 characters because “Fortran” has 7 letters. Fortran automatically pads the remaining characters with spaces.

Declaring Character Variables

Character variables can be declared with fixed or variable length. The fixed length is defined using the len attribute, while the value assigned cannot exceed the defined length. Exceeding the specified length results in truncation of the string.

Fixed-Length Character Variable

character(len=15) :: city
city = "New York"
print *, "City:", city

Output:

City: New York

Here, the variable city has a length of 15, but the string “New York” uses only 8 characters. The remaining positions are filled with spaces.

Character Variables with Single Letters

Character variables can also hold a single letter:

character(len=1) :: grade
grade = 'A'
print *, "Grade:", grade

Output:

Grade: A

This is useful for storing codes, labels, or flags that are represented by a single character.


Concatenation of Character Variables

Fortran allows concatenating two or more character variables using the // operator. Concatenation is useful for combining strings to create messages, file names, or labels.

Example:

character(len=10) :: first, last, fullname
first = "John"
last = "Doe"
fullname = first // " " // last
print *, "Full name:", fullname

Output:

Full name: John Doe

Here:

  • The // operator combines first, a space " ", and last into the variable fullname.
  • This approach allows dynamic creation of longer text from smaller strings.

Character String Slicing

Fortran provides powerful string slicing capabilities, allowing access to specific portions of a string. The syntax is:

string(start:end)

Example:

character(len=20) :: text
text = "Fortran Programming"
print *, "First 7 letters:", text(1:7)
print *, "Last 11 letters:", text(9:19)

Output:

First 7 letters: Fortran
Last 11 letters: Programming
  • text(1:7) extracts characters from position 1 to 7.
  • text(9:19) extracts characters from position 9 to 19.
  • Slicing is particularly useful for parsing and manipulating text data in programs.

Character Intrinsic Functions

Fortran provides a wide range of intrinsic functions to manipulate and process character strings. Some commonly used functions include:

  • len(string): Returns the declared length of a string.
  • len_trim(string): Returns the actual length of the string without trailing spaces.
  • trim(string): Removes trailing spaces.
  • adjustl(string): Left-justifies the string.
  • adjustr(string): Right-justifies the string.
  • index(string, substring): Returns the position of a substring within a string.

Example:

character(len=20) :: message
integer :: pos

message = " Fortran is powerful  "
print *, "Length:", len(message)
print *, "Trimmed length:", len_trim(message)
print *, "Trimmed message:", trim(message)
print *, "Left-adjusted:", adjustl(message)
print *, "Right-adjusted:", adjustr(message)

pos = index(message, "powerful")
print *, "Position of 'powerful':", pos

Output:

Length: 20
Trimmed length: 20
Trimmed message:  Fortran is powerful
Left-adjusted: Fortran is powerful  
Right-adjusted:   Fortran is powerful
Position of 'powerful': 11

These functions make it easier to manipulate and format strings for display or computation.


Reading and Writing Character Variables

Character variables can be read from the user using the read statement and printed with print or write.

Example:

character(len=20) :: username
print *, "Enter your name:"
read *, username
print *, "Hello,", trim(username)
  • The trim function removes trailing spaces for cleaner output.
  • Users can input text directly into the program, allowing interactive programs.

Assigning and Comparing Character Variables

You can assign one character variable to another, compare strings, and use them in conditional statements.

Example:

character(len=10) :: a, b
a = "Fortran"
b = "Fortran"

if (a == b) then
print *, "Strings are equal"
else
print *, "Strings are different"
end if

Output:

Strings are equal
  • Fortran allows equality (==) and inequality (/=) comparisons of strings.
  • Comparisons are case-sensitive by default.

Combining Character Variables with Other Data Types

Character variables can be combined with numeric or logical variables for formatted output using the write statement and formatting codes.

Example:

character(len=15) :: name
integer :: age

name = "Alice"
age = 25
write(*,'(A,I3)') "Name: " // name // ", Age: ", age

Output:

Name: Alice         , Age:  25
  • (A,I3) specifies a format: A for a string, I3 for a 3-digit integer.
  • This method allows professional formatting for reports or console output.

Character Arrays

Fortran allows arrays of character variables, which are useful for storing lists of strings such as names, labels, or text data.

Example:

character(len=10), dimension(3) :: names
names = (/ "Alice", "Bob", "Charlie" /)
print *, "First name:", names(1)
print *, "All names:"
print *, names

Output:

First name: Alice
All names:
Alice       Bob         Charlie
  • Character arrays provide a structured way to manage multiple text elements.

Practical Applications of Character Variables

Character variables are widely used in scientific and engineering programs for:

  1. User Interaction: Accepting names, commands, or labels.
  2. File Handling: Storing filenames, paths, and data records.
  3. Data Labels: Assigning labels to arrays, graphs, or outputs.
  4. Reporting: Formatting messages, tables, and results for display.
  5. Parsing Input: Extracting substrings, converting strings to numbers, or validating input.

Best Practices for Character Variables

  1. Define Length Appropriately: Avoid unnecessarily long lengths to save memory.
  2. Trim Strings for Output: Use trim() to remove trailing spaces.
  3. Use Intrinsic Functions: Functions like index, adjustl, and len_trim simplify string handling.
  4. Prefer Descriptive Names: Use meaningful variable names for readability.
  5. Avoid Exceeding Length: Assignments longer than len will be truncated automatically.
  6. Combine with Formatting: Use write with format specifiers for professional output.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *