I'm looking for a way to count the number of times a character occurs in a string without using SQL.
I'm relatively new to RPGLE and I've created a test program that takes user input in character format, goes through validation, and converts the successful data to numeric. One of these inputs can be a positive or negative integer. When going through validation, I test for '-' being in the first position and use %CHECK to make sure that input is 0-9 or '-'. (ex. '-10' passes, '1-0' fails)
However, if the input has multiple occurrences of the '-' symbol, such as '-1-1-1-1', it passes the validation and crashes when the program tries to convert to numeric.
I'm aware that I can use Edit codes in my DDS to have the system handle this but I'm trying to learn different ways to allow my programs to control validation. In my research, I've found that TestN and Module/Convert/%Error are methods that can be used to ensure the output is numeric, but I can't test for this specific instance so I can give meaningful feedback.
Is there a way to count the occurrences of '-' so I can test it?
Since there seems to be some confusion as to my intent, I'll add another example. If I wanted to find out how many occurrences of the letter 'L' are in the word 'HELLO', what would be the best way to go about it.
The %scan() bif accepts a 3 parameter - starting position. So you can do multiple scan's starting from the location of the last hit.
However, I'm not fond of this type of manual validation. From a performance standpoint, assuming most data is good, you're wasting cycles. More importantly, the test you've laid out, requiring '-' to be in the first position means that ' -10' would fail;
I prefer to simply do the conversion of catch the exception if need be.
monitor;
myValue = %dec(myString);
on-error;
// let the user know
endmon;
Lastly, TESTN
is obsolete and should be avoided. It probably doesn't work the way you'd want anyway. For example (IIRC), '5A' passes the TESTN test.
The RPG manual itself has this to say about TESTN:
Free-Form Syntax - (not allowed - rather than testing the variable before using it, code the usage of the variable in a MONITOR group and handle any errors with ON-ERROR. See Error-Handling Operations.)