PLC Programming SAPLC ProgrammingSOUTH AFRICA
Menu

reference · South Africa

IEC String Instructions: Parsing, Length and Capacity

IEC string instructions for PLC learners: parse barcode fields, check LEN, FIND, MID and CONCAT, preserve identifiers and test string capacity boundaries.

Conceptual IEC string instructions study workstation with a generic controller and guarded training conveyor
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

IEC string instructions help PLC programs inspect, combine and extract text for identifiers, recipe requests, messages and data exchange. Names such as LEN, CONCAT, FIND and MID describe useful operations, but correct parsing also requires a defined input format, character encoding, capacity and failure policy. A string that looks plausible on a screen is not automatically a valid request.

This guide gives South African PLC learners a strict fictional identifier parser and a bounded message-building exercise. The examples use ASCII text and independently checked expected results. They are not a barcode industry standard, a native controller test or an instruction to apply a recipe to running equipment.

This site has a commercial connection to PLC Simulator. Its learning resources do not guarantee support for arbitrary native string instructions or scanner interfaces. The illustrations are conceptual study scenes, not vendor screenshots or evidence of a customer installation.

Start with a text contract

Define what the incoming text represents and which forms are accepted. A scanner's complete message may include framing characters or a terminator, while the identifier inside that message has its own grammar. Keep reception, framing and field validation separate so the parser cannot mistake a partial message for a complete identifier.

For each interface, record the maximum payload size, encoding, delimiter rules, allowed characters and treatment of whitespace. Also specify whether letter case matters and whether leading zeroes are significant. These choices affect matching and lookup, even when the same string functions are available on both systems.

RequirementExample question
FramingHow is one complete message distinguished from part of a message?
EncodingAre the payload and parser using the same character representation?
CapacityWhat is the largest accepted payload, excluding or including framing as specified?
GrammarWhich prefixes, separators and field widths are allowed?
FailureWhat status is returned, and what existing application state stays unchanged?

Do not silently repair malformed identifiers unless a documented normalisation rule requires it. Removing spaces, changing case or truncating text can turn one input into another identity. A human-friendly display policy and a machine identifier policy may legitimately differ.

Preserve the original received value for diagnosis where appropriate, with its validity status. Keep an accepted parsed value separate. A rejected message should not inherit the previous accepted identifier while being labelled as a new successful parse.

Understand what the main string operations return

LEN concerns the current text length according to the selected implementation. CONCAT combines text. FIND locates a matching substring, while LEFT, RIGHT and MID extract portions. INSERT, DELETE and REPLACE modify a string according to position and length rules. Check exact argument names, position bases and boundary behaviour before translating an example.

Operation familyTypical purposeImportant boundary
LengthCheck whether a received field has the expected sizeCurrent length versus reserved capacity
ConcatenationBuild a message from defined partsCombined result fits the destination
SearchLocate a delimiter or markerNot-found result and repeated matches
ExtractionRead a validated sectionValid starting position and requested length
EditingChange a specified text sectionPosition shifts and resulting capacity

The CODESYS Standard 3.5.18 MID reference uses arguments STR, LEN and POS. Its example takes two characters starting at position two from SUSI and returns US. The FIND reference reports zero when the search text is absent and demonstrates positions counted from one. Consult the CODESYS MID documentation and FIND documentation.

That interface is not a promise that Siemens or Rockwell uses the same named parameters. A reference should distinguish mathematical positions from native call syntax. If a worksheet uses one-based positions while a test script uses zero-based indices, document the conversion instead of mixing the two.

For editing, specify whether the position refers to the original string or the result of an earlier edit. Deleting a section moves later positions. A parser should usually validate the original payload before performing destructive edits that remove evidence of malformed input.

Conceptual sensor, controller and conveyor showing the stages of an industrial control process
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Worked identifier: PART-12345-A2

The fictional format is exactly thirteen ASCII characters. Positions one through four contain the uppercase prefix PART. Position five is a hyphen. Positions six through ten contain exactly five ASCII digits. Position eleven is another hyphen. Position twelve is an uppercase ASCII letter, and position thirteen is one ASCII digit.

The five-digit field is called ItemCode. The final two-character field is called VariantCode. These names are part of the exercise; they do not imply a recognised barcode standard or a particular manufacturer's coding scheme.

One-based positionsRequired contentValue in PART-12345-A2
1–4Exact prefixPART
5Hyphen-
6–10Five ASCII digits12345
11Hyphen-
12–13Uppercase letter followed by digitA2

A successful parse returns ItemCode 12345 as text and VariantCode A2 as text. Extracting five characters after the first hyphen returns the item code, not the variant. The variant starts after the second hyphen and has length two.

For the same grammar, PART-00123-B7 is valid and its ItemCode remains 00123. Converting that identifier immediately to integer 123 loses its five-character representation. If a later numerical use is required, preserve the original identifier and perform a separately validated conversion for that purpose.

The parser first checks length, prefix, delimiters and character classes. Only after those checks pass does it publish the fields. With fixed positions in this exercise, a delimiter search is not necessary to locate the fields; searches can still be useful for diagnostics or for a different, explicitly variable-width grammar.

The data conversion and representation guide explains why converting a value and preserving its original representation are separate requirements. Leading zeroes are a simple example of information that can matter to an identifier even when it does not change a number.

Reject malformed and ambiguous input

The strict parser rejects any payload that does not match the complete grammar. It does not accept a valid-looking prefix followed by extra characters. Nor does it treat lowercase input as equivalent to the required uppercase form without a normalisation rule.

InputExercise outcome
PART-12345-A2Accept: item 12345, variant A2
PART-00123-B7Accept and preserve leading zeroes
PART-1234-A2Reject: wrong field width
PART-12345-A2-XReject: extra content
part-12345-A2Reject: wrong prefix case
PART-12345-a2Reject: variant letter outside the contract
PART-12X45-A2Reject: item field is not five ASCII digits
Empty payloadReject: no valid identifier

An embedded null, unexpected newline or non-ASCII character is also outside this exercise's grammar. A scanner may legitimately send carriage-return and line-feed framing, but the receiver must remove that framing according to its specified protocol before passing the payload to this strict parser. Do not silently strip arbitrary characters anywhere in the identifier.

Distinguish ASCII digits from every character that a high-level language might classify as a digit. The exercise accepts only characters 0 through 9. A broader Unicode digit predicate in a test tool can approve input that the intended ASCII interface does not support.

Return a reason that helps diagnose the failure without claiming a field is valid prematurely. Examples include incomplete frame, payload too long, wrong prefix, invalid separator or invalid character. Keep a malformed input from changing the active recipe or accepted job identity.

Parsing establishes syntax only. A syntactically valid ItemCode can still be unknown to the application. A valid VariantCode can still be incompatible with that item. Perform the relevant lookup and relationship checks before proposing or applying a change.

Illustrated study desk with a laptop, notebook and controller for planning a PLC learning route
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Search results need their own validation

In a variable-width format, a common method is to find the first delimiter, search the remaining section for a second delimiter and convert the relative result back into an absolute position. Each search must succeed before its result is used as an extraction position.

For PART-12345-A2, the first hyphen is at one-based position five. Searching the remaining text 12345-A2 finds the next hyphen at relative position six. Adding the first delimiter position gives the absolute second delimiter position eleven. The final field starts at twelve.

If the second search returns a not-found sentinel, adding the offset does not magically produce a valid delimiter. Test the sentinel first. Otherwise an apparently reasonable positive position can be calculated from a failed search and extract the wrong section.

Also decide how repeated delimiters are handled. A format allowing empty fields needs a different rule from this fixed-width exercise. PART--A2 does not become valid merely because two delimiters exist. A successful search answers where a match occurred; it does not validate all fields between matches.

Keep extraction ranges inside the validated payload. Test an empty field, a delimiter at the end and additional delimiters after an otherwise valid record. Use a worksheet that lists both relative and absolute positions to make offset mistakes visible.

Build messages within an explicit capacity

Define a second fictional contract: a message buffer can hold at most 32 ASCII payload characters. Its prefix is NOTICE followed by a colon and a space, making eight characters. The body may therefore contain at most 24 ASCII characters if the complete prefix must be preserved.

A body of exactly 24 characters produces a 32-character result and is accepted. A body of 25 characters would produce 33 and is rejected. The model does not silently truncate the body because the requirement is to preserve the complete accepted message.

Body lengthPrefix lengthRequired payload lengthExercise decision
088Accept if an empty body is permitted by this message contract
23831Accept
24832Accept at capacity
25833Reject

The example permits an empty body. Another application could reject it for semantic reasons even though capacity is sufficient. Keep size validation and content validation separate so the failure reason remains clear.

If the output protocol adds a two-character terminator inside the same 32-character capacity, the allowable body drops to 22. If framing has separate storage, document that instead. Capacity calculations must count every part that shares the buffer, including separators and formatting added after the body.

Avoid building several oversized intermediate strings before checking the final length. Bound each intermediate or use the target's supported bounded construction method. The MOVE and copy reference explains why a destination's apparent size and a successful data transfer do not establish a valid application record.

Two illustrated learners discussing a controller program beside a guarded training conveyor
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Siemens STRING length fields

Siemens' STEP 7 V20 STRING structure documentation places maximum length in the first byte and current length in the second, followed by the character data. It describes up to 254 bytes of user data. Reversing those header fields in an explanation or raw-memory interface gives the wrong model of the representation. See the Siemens STRING structure reference.

Prefer supported string operations and explicitly documented interfaces over manually altering header bytes. If a low-level interface is required, verify the exact target representation and declared capacity. Do not infer that another controller's string structure can be copied directly into this representation.

Maximum capacity is different from current content length. Reserving a larger string does not mean every position contains valid payload. The parser should operate on the accepted current payload and validate the accompanying representation before relying on it.

Rockwell STRING and CONCAT boundaries

Rockwell's Studio 5000 version 37 CONCAT reference describes the default STRING capacity as 82 characters and allows custom string types with configured capacities. It lists minor fault type 4, code 51 when a string LEN exceeds its DATA size or the combined source lengths exceed the relevant DATA capacity. This supports checking bounds, not a blanket claim that invalid LEN values simply read arbitrary garbage. See the Studio 5000 CONCAT reference.

Record the actual string type and destination capacity in the test. “STRING is 82” is insufficient when a project uses a custom type. Likewise, changing a LEN field does not allocate a larger DATA array or validate the characters already present.

Do not assume every string instruction has identical error behaviour. Check the exact operation, operand declarations and version. Capture result and status evidence for invalid-length and over-capacity cases in the native environment you intend to use.

CODESYS encoding and string size

CODESYS documents STRING storage in bytes and distinguishes Latin-1 from UTF-8 according to the compiler setting. UTF-8 characters can occupy multiple bytes, so reserved string size and visible character count do not have a universal one-to-one relationship. Its documentation also distinguishes the capacities handled by Standard and StringUtils library functions. See the CODESYS STRING datatype reference.

The exercises here deliberately use ASCII, making their stated character counts straightforward. That choice does not establish that all incoming HMI text, names or multilingual messages use the same representation. For non-ASCII text, select operations that understand the agreed encoding and verify the interface end to end.

Do not truncate an arbitrary byte sequence and assume the result is still valid encoded text. A display limit, a storage limit and a protocol limit can be different quantities. State which one a length check is enforcing.

Illustrated learner comparing controller status indicators with a guarded conveyor training model
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Receive a coherent message before parsing it

A receive buffer may be updated while application logic is running. If the parser reads a length from one update and data from another, individual fields can look valid while the combined record never existed. Use the interface's documented completion and ownership mechanism to identify a stable message.

In a teaching implementation, separate Receiving, Complete, Validated and Rejected states. Complete means the framing rule has been satisfied; it does not mean the identifier is valid. Validated means the grammar checks passed; it still does not mean the requested item is authorised for application.

If several messages arrive before the consumer finishes, define whether they are queued, rejected, overwritten with an explicit loss indication or handled by another specified method. A single string buffer alone does not establish reliable delivery of every identifier.

A duplicate message also needs a policy. The same identifier arriving twice may represent a retransmission or two separate physical items. The parser cannot resolve that distinction from character extraction alone. Use the surrounding protocol and request identity requirements.

The recipe-management guide shows why a parsed request should be checked before it becomes an active selection. Preserve the previous accepted state when a new request fails its required checks.

Test string handling with useful counterexamples

Start with valid examples whose fields are deliberately different. PART-12345-A2 reveals a parser that returns the item field when asked for the variant. A payload whose fields accidentally contain similar text can conceal that mistake.

Test field-width boundaries, every separator, missing and additional content, leading zeroes, lowercase input and non-ASCII characters. Include transport framing tests separately from grammar tests. The expected result should state both the acceptance status and every extracted field.

For the capacity exercise, test exactly one below the limit, exactly at it and one above it. Add framing to the calculation if it shares storage. Verify that rejection does not publish a partial message as complete.

Use PLC program-testing practice to organise these cases. Check the current exercise scope; the mathematical and text-model checks here do not demonstrate native scanner communication or vendor instruction fault behaviour.

Questions about PLC strings and barcode parsing

Why does MID return the wrong barcode field?

Check the validated field position, requested length and the implementation's position base. In the fictional example, the item starts at position six while the variant starts at twelve. A second-delimiter search is pointless if the extraction still uses the first delimiter's offset.

Can I make every identifier uppercase before matching?

Only when the interface contract defines case-insensitive identity or an agreed normalisation rule. Otherwise changing case changes the received value. The strict exercise accepts an exact uppercase grammar and rejects lowercase input rather than silently repairing it.

Is LEN the same as string capacity?

No. Current content length and reserved capacity answer different questions. The native representation and encoding determine how length is stored or reported. Use the actual declaration and documentation instead of inferring capacity from the visible text.

Should I convert a numeric-looking item code to INT?

Not automatically. An identifier such as 00123 may require its leading zeroes for matching and display. Preserve it as text unless the application needs a separate numeric value, and then validate range and conversion without discarding the original identifier.

What should a South African PLC course assess here?

Ask for a parser that rejects malformed data, preserves identifiers and demonstrates capacity boundaries. Learners comparing training in Gauteng, Durban or Cape Town can request the same evidence, along with the actual controller and software version. A successful normal barcode alone is a weak assessment.

Illustrated PLC project portfolio with a process diagram, test notes and a laptop showing logic
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Keep the parser and its limits reviewable

Save the input grammar, position worksheet, capacity calculation and expected test results beside the implementation. Identify which checks are text-model tests and which were run in native engineering software. Include at least one deliberately malformed message and show that it leaves the active application state unchanged.

For further expression practice, explore Structured Text learning exercises, checking the current access terms and available operations. Present the work as a bounded learning example with clear evidence.

Useful string handling starts before LEN or MID is called. Once framing, grammar, encoding, capacity and failure behaviour are explicit, the individual instructions can be chosen and tested against a complete requirement.

By PLC Programming SA · Last updated 2026-09-12