INSPECT vs. UNSTRING in COBOL: Mastering String Manipulation ????
1?? INSPECT – The Quick Way to Analyze and Modify Strings
The INSPECT statement is used to count, replace, or convert occurrences of specific characters or substrings within a string.
?? INSPECT to Count Occurrences
Imagine you need to count how many times the letter "A" appears in a string:
INSPECT WS-TEXT TALLYING WS-COUNT FOR ALL 'A'.
?? Use Case: Perfect for counting characters or words in a string.
?? INSPECT to Replace Characters
If you want to replace all spaces (' ') with hyphens ('-'), you can do:
INSPECT WS-TEXT REPLACING ALL ' ' BY '-'.
?? Use Case: Great for formatting output or standardizing data.
2?? UNSTRING – Splitting Strings Into Pieces
The UNSTRING statement is used to break a string into multiple fields based on a delimiter.
?? UNSTRING Example: Splitting a Full Name
Let’s say we receive a name as "John Doe" and need to split it into first name and last name:
UNSTRING WS-NAME DELIMITED BY ' ' INTO WS-FIRST-NAME WS-LAST-NAME.
?? Use Case: Best for extracting parts of a string, such as CSV data, names, or codes.
?? UNSTRING with Multiple Delimiters
Need to split "John|Doe|Developer"? You can use multiple delimiters:
UNSTRING WS-NAME DELIMITED BY '|' INTO WS-FIRST-NAME WS-LAST-NAME WS-JOB.
3?? INSPECT vs. UNSTRING – When to Use Each?
?? Best Practice: If you need to analyze or modify text, use INSPECT. If you need to break it into pieces, use UNSTRING.
Senior Mobile Developer | Android Software Engineer | Jetpack Compose | GraphQL | Kotlin | Java | React Native | Swift
1 周Great article!
Android Developer | Mobile Software Engineer | Kotlin | Jetpack Compose | XML
1 周Nice content, thanks for sharing!!
Senior Software Engineer | Java | Spring Boot | React | Angular | AWS | APIs
1 周Strong case made here
Senior Front-end Developer | React - NextJS - Typescript - NodeJS - AWS
1 周Nice Post! Thank you for sharing!