MainframeMaster

COBOL Tutorial

COBOL String Operations

Progress0 of 0 lessons

String Operations Overview

COBOL provides powerful string manipulation capabilities through several specialized statements and functions. These operations allow you to concatenate, split, search, replace, and analyze string data efficiently.

Main String Operations

COBOL offers four primary string manipulation tools:

  1. STRING - Concatenate multiple strings into one
  2. UNSTRING - Split a string into multiple parts
  3. INSPECT - Search, replace, or count characters in a string
  4. String Functions - Built-in functions for string analysis

Each operation serves specific purposes and can be combined for complex string processing.

Common Use Cases

OperationUse CaseExample
STRINGBuilding full names, addresses, messagesFirst + Last name
UNSTRINGParsing CSV data, splitting delimited fieldsComma-separated values
INSPECTData cleaning, character replacementRemove spaces, convert case
FunctionsLength checking, trimming, validationGet string length, trim spaces

STRING Statement

The STRING statement concatenates multiple source strings into a single target string. It provides flexible control over how strings are combined and handles overflow conditions.

Basic Syntax

cobol
1
2
3
4
5
6
7
STRING {source-string-1} DELIMITED BY {delimiter-1} {source-string-2} DELIMITED BY {delimiter-2} ... INTO target-string [ON OVERFLOW imperative-statement] [NOT ON OVERFLOW imperative-statement] [END-STRING]

The STRING statement combines multiple source strings into the target string, using DELIMITED BY to control when each source string ends.

DELIMITED BY Options

The DELIMITED BY clause specifies when to stop processing each source string:

OptionDescriptionExample
SIZEUse entire field (including spaces)DELIMITED BY SIZE
SPACEStop at first spaceDELIMITED BY SPACE
SPACESStop at first spaceDELIMITED BY SPACES
CharacterStop at specified characterDELIMITED BY ","
IdentifierStop at value in fieldDELIMITED BY WS-DELIMITER

Basic Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
* Simple concatenation STRING FIRST-NAME DELIMITED BY SPACE, LAST-NAME DELIMITED BY SIZE INTO FULL-NAME. * With literal strings STRING "Hello, " DELIMITED BY SIZE, CUSTOMER-NAME DELIMITED BY SPACE, "!" DELIMITED BY SIZE INTO GREETING-MESSAGE. * Using different delimiters STRING FIELD1 DELIMITED BY ",", FIELD2 DELIMITED BY SIZE INTO COMBINED-FIELD. * With overflow handling STRING FIELD1 DELIMITED BY SIZE, FIELD2 DELIMITED BY SIZE INTO TARGET-FIELD ON OVERFLOW PERFORM ERROR-HANDLING NOT ON OVERFLOW DISPLAY "String operation successful" END-STRING.

These examples show various ways to use the STRING statement for different concatenation needs.

Advanced STRING Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
* Building addresses STRING STREET-ADDRESS DELIMITED BY SPACE, ", " DELIMITED BY SIZE, CITY DELIMITED BY SPACE, ", " DELIMITED BY SIZE, STATE DELIMITED BY SPACE, " " DELIMITED BY SIZE, ZIP-CODE DELIMITED BY SIZE INTO FULL-ADDRESS. * Creating formatted messages STRING "Customer ID: " DELIMITED BY SIZE, CUSTOMER-ID DELIMITED BY SIZE, " Name: " DELIMITED BY SIZE, CUSTOMER-NAME DELIMITED BY SPACE, " Amount: $" DELIMITED BY SIZE, AMOUNT DELIMITED BY SIZE INTO LOG-MESSAGE. * With conditional concatenation IF CUSTOMER-TYPE = "VIP" STRING "VIP " DELIMITED BY SIZE, CUSTOMER-NAME DELIMITED BY SPACE INTO DISPLAY-NAME ELSE STRING CUSTOMER-NAME DELIMITED BY SPACE INTO DISPLAY-NAME END-IF.

Advanced examples demonstrate complex string building scenarios with multiple fields and conditional logic.

UNSTRING Statement

The UNSTRING statement parses a source string and splits it into multiple target fields based on delimiters. It's the opposite of STRING and is useful for parsing delimited data.

Basic Syntax

cobol
1
2
3
4
5
6
7
8
9
10
UNSTRING source-string DELIMITED BY {delimiter-1} [OR {delimiter-2}] ... INTO target-field-1 [DELIMITER IN delimiter-field-1] target-field-2 [DELIMITER IN delimiter-field-2] ... [WITH POINTER pointer-field] [TALLYING IN tally-field] [ON OVERFLOW imperative-statement] [NOT ON OVERFLOW imperative-statement] [END-UNSTRING]

The UNSTRING statement splits the source string into multiple target fields, using delimiters to determine where to split.

Basic Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
* Simple splitting by comma UNSTRING CSV-LINE DELIMITED BY "," INTO FIELD1, FIELD2, FIELD3. * Splitting by multiple delimiters UNSTRING INPUT-LINE DELIMITED BY "," OR ";" OR SPACE INTO NAME-FIELD, ADDRESS-FIELD, PHONE-FIELD. * With delimiter tracking UNSTRING PARSED-LINE DELIMITED BY "," INTO FIELD1 DELIMITER IN DELIM1, FIELD2 DELIMITER IN DELIM2, FIELD3 DELIMITER IN DELIM3. * With pointer and tally UNSTRING SOURCE-STRING DELIMITED BY SPACE INTO TARGET1, TARGET2, TARGET3 WITH POINTER WS-POSITION TALLYING IN WS-FIELD-COUNT.

These examples demonstrate different ways to use UNSTRING for parsing delimited data.

Advanced UNSTRING Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
* Parsing CSV data UNSTRING CSV-RECORD DELIMITED BY "," INTO CUSTOMER-ID DELIMITER IN WS-DELIM1, CUSTOMER-NAME DELIMITER IN WS-DELIM2, CUSTOMER-ADDRESS DELIMITER IN WS-DELIM3, CUSTOMER-PHONE DELIMITER IN WS-DELIM4 WITH POINTER WS-POSITION TALLYING IN WS-FIELD-COUNT ON OVERFLOW PERFORM HANDLE-OVERFLOW NOT ON OVERFLOW DISPLAY "Parsed " WS-FIELD-COUNT " fields" END-UNSTRING. * Parsing fixed-format with variable delimiters UNSTRING LOG-ENTRY DELIMITED BY "|" OR ":" OR SPACE INTO TIMESTAMP DELIMITER IN WS-TIME-DELIM, LOG-LEVEL DELIMITER IN WS-LEVEL-DELIM, MESSAGE DELIMITER IN WS-MSG-DELIM. * Parsing with conditional logic IF RECORD-TYPE = "CUSTOMER" UNSTRING CUSTOMER-LINE DELIMITED BY "," INTO CUST-ID, CUST-NAME, CUST-ADDRESS ELSE UNSTRING PRODUCT-LINE DELIMITED BY "|" INTO PROD-ID, PROD-NAME, PROD-PRICE END-IF.

Advanced examples show complex parsing scenarios with error handling and conditional processing.

UNSTRING Options and Clauses

ClausePurposeExample
DELIMITED BYSpecify delimiter(s) for splittingDELIMITED BY ","
DELIMITER INStore the delimiter usedDELIMITER IN WS-DELIM
WITH POINTERTrack position in source stringWITH POINTER WS-POS
TALLYING INCount fields processedTALLYING IN WS-COUNT
ON OVERFLOWHandle overflow conditionsON OVERFLOW PERFORM ERROR

INSPECT Statement

The INSPECT statement analyzes and modifies strings by counting, replacing, or converting characters. It's a powerful tool for string manipulation and data cleaning.

Basic Syntax

cobol
1
2
3
4
5
INSPECT target-string TALLYING count-field FOR {ALL | LEADING | FIRST} {characters | identifier} [REPLACING {ALL | LEADING | FIRST} {characters | identifier} BY {characters | identifier}] [CONVERTING {characters | identifier} TO {characters | identifier}] [END-INSPECT]

INSPECT can perform counting, replacing, and converting operations on strings.

INSPECT TALLYING Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
* Count all occurrences of a character INSPECT TEXT-FIELD TALLYING WS-COUNT FOR ALL "A". * Count leading spaces INSPECT NAME-FIELD TALLYING WS-SPACE-COUNT FOR LEADING SPACE. * Count first occurrence INSPECT ADDRESS-FIELD TALLYING WS-COMMA-COUNT FOR FIRST ",". * Count multiple characters INSPECT DATA-FIELD TALLYING WS-VOWEL-COUNT FOR ALL "A" "E" "I" "O" "U". * Count with identifier INSPECT INPUT-FIELD TALLYING WS-DIGIT-COUNT FOR ALL WS-DIGITS.

TALLYING counts occurrences of specified characters in the target string.

INSPECT REPLACING Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
* Replace all occurrences INSPECT TEXT-FIELD REPLACING ALL "A" BY "X". * Replace leading characters INSPECT NAME-FIELD REPLACING LEADING SPACE BY "0". * Replace first occurrence INSPECT ADDRESS-FIELD REPLACING FIRST "," BY " - ". * Replace multiple characters INSPECT DATA-FIELD REPLACING ALL "A" BY "X" ALL "B" BY "Y" ALL "C" BY "Z". * Replace with identifier INSPECT INPUT-FIELD REPLACING ALL WS-OLD-CHAR BY WS-NEW-CHAR.

REPLACING substitutes characters in the target string based on specified rules.

INSPECT CONVERTING Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
* Convert case (lower to upper) INSPECT TEXT-FIELD CONVERTING "abcdefghijklmnopqrstuvwxyz" TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ". * Convert case (upper to lower) INSPECT NAME-FIELD CONVERTING "ABCDEFGHIJKLMNOPQRSTUVWXYZ" TO "abcdefghijklmnopqrstuvwxyz". * Convert specific characters INSPECT DATA-FIELD CONVERTING "0123456789" TO "ABCDEFGHIJ". * Convert with identifiers INSPECT INPUT-FIELD CONVERTING WS-SOURCE-CHARS TO WS-TARGET-CHARS.

CONVERTING transforms characters from one set to another, useful for case conversion and character mapping.

Combined INSPECT Operations

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
* Count and replace in one operation INSPECT TEXT-FIELD TALLYING WS-SPACE-COUNT FOR ALL SPACE REPLACING ALL SPACE BY "-". * Multiple operations INSPECT DATA-FIELD TALLYING WS-COMMA-COUNT FOR ALL "," REPLACING ALL "," BY ";" CONVERTING "abcdefghijklmnopqrstuvwxyz" TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ". * Complex data cleaning INSPECT INPUT-FIELD TALLYING WS-SPACE-COUNT FOR LEADING SPACE REPLACING LEADING SPACE BY "0" ALL " " BY " " ALL "A" BY "X" CONVERTING "abcdefghijklmnopqrstuvwxyz" TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ".

INSPECT can combine multiple operations for complex string manipulation.

String Functions

COBOL provides several built-in functions for string analysis and manipulation. These functions return values that can be used in expressions and calculations.

Common String Functions

FunctionPurposeExampleResult
FUNCTION LENGTHGet string length (no trailing spaces)FUNCTION LENGTH("ABC ")3
FUNCTION TRIMRemove leading/trailing spacesFUNCTION TRIM(" ABC ")"ABC"
FUNCTION UPPER-CASEConvert to uppercaseFUNCTION UPPER-CASE("abc")"ABC"
FUNCTION LOWER-CASEConvert to lowercaseFUNCTION LOWER-CASE("ABC")"abc"
FUNCTION REVERSEReverse string charactersFUNCTION REVERSE("ABC")"CBA"

Function Usage Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
* Get string length COMPUTE WS-LENGTH = FUNCTION LENGTH(WS-STRING). * Trim spaces MOVE FUNCTION TRIM(WS-INPUT) TO WS-CLEAN-STRING. * Convert case MOVE FUNCTION UPPER-CASE(WS-NAME) TO WS-UPPER-NAME. MOVE FUNCTION LOWER-CASE(WS-CODE) TO WS-LOWER-CODE. * Reverse string MOVE FUNCTION REVERSE(WS-PALINDROME) TO WS-REVERSED. * Combined operations COMPUTE WS-CLEAN-LENGTH = FUNCTION LENGTH(FUNCTION TRIM(WS-STRING)). * In conditional statements IF FUNCTION LENGTH(WS-NAME) > 10 DISPLAY "Name too long" END-IF. * In calculations COMPUTE WS-POSITION = FUNCTION LENGTH(WS-PREFIX) + 1.

String functions can be used in expressions, assignments, and conditional statements.

Advanced Function Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
* Data validation with functions IF FUNCTION LENGTH(FUNCTION TRIM(WS-CUSTOMER-NAME)) = 0 DISPLAY "Customer name is required" MOVE "ERROR" TO WS-STATUS END-IF. * Case-insensitive comparison IF FUNCTION UPPER-CASE(WS-INPUT) = FUNCTION UPPER-CASE(WS-EXPECTED) MOVE "MATCH" TO WS-RESULT END-IF. * String formatting STRING FUNCTION TRIM(WS-FIRST-NAME) DELIMITED BY SIZE, " " DELIMITED BY SIZE, FUNCTION TRIM(WS-LAST-NAME) DELIMITED BY SIZE INTO WS-FULL-NAME. * Palindrome checking IF WS-STRING = FUNCTION REVERSE(WS-STRING) DISPLAY "String is a palindrome" END-IF. * Dynamic field sizing COMPUTE WS-FIELD-SIZE = FUNCTION LENGTH(WS-DATA) + 5.

Advanced examples show how functions can be combined for complex string processing.

Practical Examples

These examples demonstrate real-world applications of COBOL string operations for common business scenarios.

Example 1: Customer Data Processing

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
* Process customer data with string operations PROCESS-CUSTOMER-DATA. * Clean and format customer name INSPECT WS-CUSTOMER-NAME TALLYING WS-SPACE-COUNT FOR LEADING SPACE REPLACING LEADING SPACE BY "0" ALL " " BY " " END-INSPECT * Convert name to proper case INSPECT WS-CUSTOMER-NAME CONVERTING "abcdefghijklmnopqrstuvwxyz" TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ" END-INSPECT * Build full address STRING WS-STREET-ADDRESS DELIMITED BY SPACE, ", " DELIMITED BY SIZE, WS-CITY DELIMITED BY SPACE, ", " DELIMITED BY SIZE, WS-STATE DELIMITED BY SIZE, " " DELIMITED BY SIZE, WS-ZIP-CODE DELIMITED BY SIZE INTO WS-FULL-ADDRESS ON OVERFLOW PERFORM HANDLE-ADDRESS-OVERFLOW NOT ON OVERFLOW DISPLAY "Address formatted successfully" END-STRING * Validate email format IF FUNCTION LENGTH(FUNCTION TRIM(WS-EMAIL)) > 0 INSPECT WS-EMAIL TALLYING WS-AT-COUNT FOR ALL "@" END-INSPECT IF WS-AT-COUNT NOT = 1 DISPLAY "Invalid email format" END-IF END-IF.

This example shows comprehensive customer data processing using multiple string operations for cleaning, formatting, and validation.

Example 2: CSV File Processing

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
* Process CSV data with UNSTRING PROCESS-CSV-LINE. * Parse CSV line into fields UNSTRING WS-CSV-LINE DELIMITED BY "," INTO WS-FIELD1 DELIMITER IN WS-DELIM1, WS-FIELD2 DELIMITER IN WS-DELIM2, WS-FIELD3 DELIMITER IN WS-DELIM3, WS-FIELD4 DELIMITER IN WS-DELIM4 WITH POINTER WS-POSITION TALLYING IN WS-FIELD-COUNT ON OVERFLOW PERFORM HANDLE-CSV-OVERFLOW NOT ON OVERFLOW PERFORM VALIDATE-CSV-FIELDS END-UNSTRING. VALIDATE-CSV-FIELDS. * Clean each field PERFORM CLEAN-FIELD VARYING WS-I FROM 1 BY 1 UNTIL WS-I > WS-FIELD-COUNT. CLEAN-FIELD. EVALUATE WS-I WHEN 1 INSPECT WS-FIELD1 TALLYING WS-SPACE-COUNT FOR LEADING SPACE REPLACING LEADING SPACE BY "0" END-INSPECT WHEN 2 INSPECT WS-FIELD2 TALLYING WS-SPACE-COUNT FOR LEADING SPACE REPLACING LEADING SPACE BY "0" END-INSPECT WHEN 3 INSPECT WS-FIELD3 TALLYING WS-SPACE-COUNT FOR LEADING SPACE REPLACING LEADING SPACE BY "0" END-INSPECT WHEN 4 INSPECT WS-FIELD4 TALLYING WS-SPACE-COUNT FOR LEADING SPACE REPLACING LEADING SPACE BY "0" END-INSPECT END-EVALUATE.

This example demonstrates parsing and cleaning CSV data using UNSTRING and INSPECT operations.

Example 3: Report Generation

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
* Generate formatted report lines GENERATE-REPORT-LINE. * Build header line STRING "CUSTOMER REPORT" DELIMITED BY SIZE, " - " DELIMITED BY SIZE, FUNCTION TRIM(WS-REPORT-DATE) DELIMITED BY SIZE, " - Page " DELIMITED BY SIZE, WS-PAGE-NUMBER DELIMITED BY SIZE INTO WS-HEADER-LINE END-STRING * Build detail line STRING WS-CUSTOMER-ID DELIMITED BY SIZE, " | " DELIMITED BY SIZE, FUNCTION TRIM(WS-CUSTOMER-NAME) DELIMITED BY SIZE, " | " DELIMITED BY SIZE, WS-CUSTOMER-AMOUNT DELIMITED BY SIZE, " | " DELIMITED BY SIZE, FUNCTION UPPER-CASE(WS-CUSTOMER-STATUS) DELIMITED BY SIZE INTO WS-DETAIL-LINE END-STRING * Build summary line STRING "TOTAL CUSTOMERS: " DELIMITED BY SIZE, WS-CUSTOMER-COUNT DELIMITED BY SIZE, " | TOTAL AMOUNT: $" DELIMITED BY SIZE, WS-TOTAL-AMOUNT DELIMITED BY SIZE INTO WS-SUMMARY-LINE END-STRING.

This example shows how string operations are used to format report lines with proper spacing and alignment.

Best Practices and Tips

Following these best practices ensures efficient and reliable string operations in COBOL programs.

General Best Practices

  • Always handle overflow conditions in STRING operations
  • Use appropriate delimiters for your data format
  • Validate input data before string operations
  • Use meaningful field names for clarity
  • Test with various data scenarios including edge cases
  • Consider performance implications of complex string operations

Performance Considerations

  • Use DELIMITED BY SPACE instead of SIZE when possible
  • Combine multiple INSPECT operations into single statements
  • Avoid unnecessary string operations in loops
  • Use appropriate field sizes to minimize memory usage
  • Consider using functions for simple operations

Error Handling Guidelines

  • Always include ON OVERFLOW clauses for STRING operations
  • Validate field sizes before string operations
  • Check for null or empty strings before processing
  • Handle delimiter not found scenarios in UNSTRING
  • Log string operation errors for debugging
  • Provide meaningful error messages for users

Common Pitfalls to Avoid

  • Forgetting overflow handling in STRING operations
  • Using wrong delimiters for data format
  • Not initializing tally fields before INSPECT operations
  • Ignoring field size limitations in target fields
  • Not validating input data before string operations
  • Using complex nested operations without proper testing
  • Forgetting to handle empty strings in UNSTRING operations

Test Your Knowledge

1. What is the primary purpose of the STRING statement in COBOL?

  • To split a string into multiple parts
  • To concatenate multiple strings into one
  • To search for patterns in a string
  • To convert string case

2. Which statement is used to split a string into multiple parts?

  • STRING
  • UNSTRING
  • INSPECT
  • MOVE

3. What does the INSPECT statement do in COBOL?

  • Concatenate strings
  • Split strings
  • Search, replace, or count characters in a string
  • Convert string format

4. What is the purpose of the DELIMITED BY clause in STRING and UNSTRING?

  • To specify the target field
  • To define the end condition for string operations
  • To set the starting position
  • To define error handling

5. Which function returns the length of a string in COBOL?

  • LENGTH
  • SIZE
  • LEN
  • FUNCTION LENGTH

Frequently Asked Questions