In this section, we will explore how to handle strings in Fortran. Strings are sequences of characters and are essential for various programming tasks, such as reading user input, displaying messages, and manipulating text data. We will cover the following topics:
- Declaring and Initializing Strings
- String Operations
- String Intrinsic Functions
- Practical Examples
- Exercises
- Declaring and Initializing Strings
In Fortran, strings are declared using the CHARACTER data type. You can specify the length of the string using the LEN attribute.
Syntax:
Example:
PROGRAM StringExample IMPLICIT NONE CHARACTER(LEN=20) :: greeting greeting = 'Hello, Fortran!' PRINT *, greeting END PROGRAM StringExample
Explanation:
CHARACTER(LEN=20) :: greetingdeclares a string variablegreetingwith a maximum length of 20 characters.greeting = 'Hello, Fortran!'initializes the string with the value 'Hello, Fortran!'.PRINT *, greetingprints the string to the console.
- String Operations
Concatenation:
You can concatenate strings using the // operator.
Example:
PROGRAM ConcatenateStrings IMPLICIT NONE CHARACTER(LEN=10) :: firstName, lastName CHARACTER(LEN=21) :: fullName firstName = 'John' lastName = 'Doe' fullName = firstName // ' ' // lastName PRINT *, fullName END PROGRAM ConcatenateStrings
Explanation:
fullName = firstName // ' ' // lastNameconcatenatesfirstName, a space, andlastNameto formfullName.
Substring:
You can extract a substring using the substring notation string(start:end).
Example:
PROGRAM SubstringExample IMPLICIT NONE CHARACTER(LEN=20) :: sentence CHARACTER(LEN=5) :: word sentence = 'Fortran Programming' word = sentence(1:5) PRINT *, word END PROGRAM SubstringExample
Explanation:
word = sentence(1:5)extracts the substring from position 1 to 5, resulting in 'Fortr'.
- String Intrinsic Functions
Fortran provides several intrinsic functions for string manipulation. Here are some commonly used ones:
| Function | Description | Example Usage |
|---|---|---|
LEN(string) |
Returns the length of the string | LEN('Hello') returns 5 |
TRIM(string) |
Removes trailing spaces from the string | TRIM('Hello ') returns 'Hello' |
ADJUSTL(string) |
Left-justifies the string | ADJUSTL(' Hello') returns 'Hello' |
ADJUSTR(string) |
Right-justifies the string | ADJUSTR('Hello ') returns ' Hello' |
INDEX(string, substring) |
Returns the position of the substring in the string | INDEX('Fortran', 'tran') returns 4 |
Example:
PROGRAM StringFunctions IMPLICIT NONE CHARACTER(LEN=20) :: text INTEGER :: position text = ' Fortran ' PRINT *, 'Length:', LEN(text) PRINT *, 'Trimmed:', TRIM(text) PRINT *, 'Left-justified:', ADJUSTL(text) PRINT *, 'Right-justified:', ADJUSTR(text) position = INDEX(text, 'For') PRINT *, 'Position of "For":', position END PROGRAM StringFunctions
Explanation:
LEN(text)returns the length oftext.TRIM(text)removes trailing spaces.ADJUSTL(text)left-justifies the string.ADJUSTR(text)right-justifies the string.INDEX(text, 'For')returns the position of the substring 'For' intext.
- Practical Examples
Example 1: Reversing a String
PROGRAM ReverseString
IMPLICIT NONE
CHARACTER(LEN=20) :: original, reversed
INTEGER :: i, len
original = 'Fortran'
len = LEN_TRIM(original)
DO i = 1, len
reversed(i:i) = original(len-i+1:len-i+1)
END DO
PRINT *, 'Original:', TRIM(original)
PRINT *, 'Reversed:', TRIM(reversed)
END PROGRAM ReverseStringExplanation:
LEN_TRIM(original)returns the length oforiginalwithout trailing spaces.- The loop reverses the string by assigning characters from the end of
originalto the beginning ofreversed.
Example 2: Counting Vowels in a String
PROGRAM CountVowels
IMPLICIT NONE
CHARACTER(LEN=100) :: text
INTEGER :: i, len, count
CHARACTER(LEN=1) :: ch
text = 'Fortran is a powerful language.'
len = LEN_TRIM(text)
count = 0
DO i = 1, len
ch = text(i:i)
IF (ch == 'A' .OR. ch == 'E' .OR. ch == 'I' .OR. ch == 'O' .OR. ch == 'U' .OR. &
ch == 'a' .OR. ch == 'e' .OR. ch == 'i' .OR. ch == 'o' .OR. ch == 'u') THEN
count = count + 1
END IF
END DO
PRINT *, 'Number of vowels:', count
END PROGRAM CountVowelsExplanation:
- The loop iterates through each character in
text. - The
IFstatement checks if the character is a vowel and increments thecountif true.
- Exercises
Exercise 1: Palindrome Checker
Write a program that checks if a given string is a palindrome (reads the same forwards and backwards).
Solution:
PROGRAM PalindromeChecker
IMPLICIT NONE
CHARACTER(LEN=100) :: text, reversed
INTEGER :: i, len
LOGICAL :: isPalindrome
text = 'madam'
len = LEN_TRIM(text)
reversed = ''
DO i = 1, len
reversed(i:i) = text(len-i+1:len-i+1)
END DO
isPalindrome = (TRIM(text) == TRIM(reversed))
IF (isPalindrome) THEN
PRINT *, 'The string is a palindrome.'
ELSE
PRINT *, 'The string is not a palindrome.'
END IF
END PROGRAM PalindromeCheckerExercise 2: String Length without Using LEN
Write a program to find the length of a string without using the LEN function.
Solution:
PROGRAM StringLength
IMPLICIT NONE
CHARACTER(LEN=100) :: text
INTEGER :: i, length
text = 'Fortran'
length = 0
DO i = 1, 100
IF (text(i:i) == ' ') EXIT
length = length + 1
END DO
PRINT *, 'Length of the string:', length
END PROGRAM StringLengthConclusion
In this section, we covered the basics of string handling in Fortran, including declaring and initializing strings, performing string operations, and using intrinsic functions. We also provided practical examples and exercises to reinforce the concepts. Understanding string manipulation is crucial for effective programming in Fortran, and these skills will be useful in various applications. In the next section, we will delve into array handling, which is another fundamental aspect of Fortran programming.
Fortran Programming Course
Module 1: Introduction to Fortran
- Introduction to Fortran
- Setting Up the Development Environment
- Basic Syntax and Structure
- Writing Your First Fortran Program
Module 2: Basic Concepts
- Variables and Data Types
- Operators and Expressions
- Input and Output
- Control Structures: If Statements
- Control Structures: Loops
Module 3: Arrays and Strings
Module 4: Procedures and Functions
Module 5: Advanced Data Structures
Module 6: File Handling
Module 7: Advanced Topics
Module 8: Best Practices and Optimization
- Code Optimization Techniques
- Debugging and Profiling
- Writing Maintainable Code
- Fortran Standards and Portability
