Custom Count of Lines in a Text

Whereas the count of characters in a string is well-defined, and may be zero,
the count of lines in a string has no natural definition, and requires the adoption of some arbitrary convention.

  • A list of strings can be empty [ ], and contain no strings at all, but even an empty string is still a string, and we could either think of it, in list terms, as [""] with a line count of 1, or as somehow auto-magically equivalent to [ ], with a line count of 0.
  • More generally, we can decide to either count, or ignore, blank lines of three kinds:
    1. Those before the first non-empty ('printing') lines,
    2. those between printing lines, and
    3. those trailing after the last printing line.

Here is an illustration of using a subroutine to define whichever line counting convention you want to use.

In this case, we are choosing to:

  • give a line count of 0 to an empty string, and
  • count all other strings as the length of the list created by splitting on the line-delimiter.

Test using custom subroutine

TEST CUSTOM NUMBER OF LINES IN A STRING.kmmacros (3.4 KB)


Subroutine

Number of lines in a string- with an empty string returning 0.kmmacros (2.4 KB)

1 Like

This is a good contribution to the community. Many people will need to be referred to this in the future.

For the "empty is zero lines, otherwise line count" case you can have fun with a ternary:

%Calculate%CHARACTERS(%Variable%Local_text%) = 0 ? 0 : LINES(%%Variable%Local_text%)%

1 Like

Yes, or use a Set Variable to Calculation with...

LINES(%Variable%local_List%)*(CHARACTERS(%Variable%local_List%)>0)

This subject was recently discussed in another thread.

Yep, I replied here before getting to the thread that spawned this one.

This still makes me itch in that you're always making two function calls, yet LINES() is unnecessary if CHARACTERS() is zero. But I think the KM ternary does the same, since

1 = 1 ? 1 : ( 1/0 )

...throws a "failed to evaluate" because of the divide-by-zero error -- the "else" being evaluated even though it isn't used. Compare that with the full "If... Then... Else..." version:

...which has no such problem.

Your itches are our gain, @Nige_S. You always do a great job explaining concepts.

BTW, in the other thread, @Airy suggested the ternary operator method. I like it better; I’ve used that operator many times before, but sometimes I forget. :relieved_face:

Since I hold Nige up to the highest esteem, it's a thrill for one of my answers to be preferred over Nige's.

I think it's the same answer, except I use the reverse logic to yours. Again, force of habit -- I find = 0 ? 0 easier to mentally parse than > 0 ? LINES().

Sorry to burst your bubble, @Airy, but in this case you are only equivalent to @Nige_S as he also suggested the ternary operator.

Sorry, you'll have to be satisfied knowing that your solution was better than mine. :grinning_face:

1 Like